Can I instantiate a PHP class inside another class?

前端 未结 8 840
挽巷
挽巷 2020-12-08 03:57

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 constructo

8条回答
  •  感动是毒
    2020-12-08 04:32

    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

提交回复
热议问题