Can I instantiate a PHP class inside another class?

class, object, oop, php

Solution

You can't define a class in another class. You should include files with other classes outside of the class. In your case, that will give you two top-level classes `db` and `some`. Now in the constructor of `some` you can decide to create an instance of `db`. For example:

include SITE_ROOT . 'applicatie/' . 'db.class.php';

class some {

    public function __construct() {
        if (...) {
            $this->db = new db;
        }
    }

}

Problem

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 ```

Original source

Related problems