Richard Richard - 5 months ago 7
PHP Question

Can I instantiate a PHP class inside another class?

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{

include SITE_ROOT . 'applicatie/' . 'db.class.php';
$db=new db


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 __construct() {
        if (...) {
            $this->db = new db;