Can I instantiate a PHP class inside another class?

Viewed 72639

I was wondering if it is allowed to create an instance of a class inside another class.

Or, do I have to create it outside and then pass it in through the constructor? But then I would have created it without knowing if I would need it.

Example (a database class):

class some{

if(.....){
include SITE_ROOT . 'applicatie/' . 'db.class.php';
$db=new db
8 Answers

I just wanted to point out that it is possible to load a class definition dynamically inside another class definition.

Lukas is right that we cannot define a class inside another class, but we can include() or require() them dynamically, since every functions and classes defined in the included file will have a global scope. If you need to load a class or function dynamically, simply include the files in one of the class' functions. You can do this:

function some()
{
    require('db.php');
    $db = new Db();
    ...
}

http://php.net/manual/en/function.include.php

I'm just seeing this now and I wish to add my comment. It could be of benefit to anyone. Has anyone heard of php traits? Although traits does not import another class but only imports a trait into another class. So instead of trying to import several classes, you can have a main classe while the subclasses will act like traits making it possible for you to use them in main/parent classes

Related