PHP access class inside another class

后端 未结 5 1117
独厮守ぢ
独厮守ぢ 2021-01-12 09:57

So I have two classes like this:

class foo {
    /* code here */
}
$foo = new foo();
class bar {
    global $foo;
    public function bar () {
        echo $         


        
5条回答
  •  一向
    一向 (楼主)
    2021-01-12 10:18

    An option is to autoload your classes. Also, if you make your class a static class, you can call it without $classname = new classname():

    //Autoloader
    spl_autoload_register(function ($class) {
    $classDir = '/_class/';
    $classExt = '.php';
    include $_SERVER['DOCUMENT_ROOT'] . $classDir . $class . $classExt;
    });
    
    //Your code
    class bar {
        private static $foo = null; //to store the class instance
    
        public function __construct(){
            self::$foo = new foo(); //stores an instance of Foo into the class' property
        }
    
        public function bar () {
            echo self::$foo->something();
        }
    }
    

    If you convert your class (foo) into a static class

    //Autoloader
    spl_autoload_register(function ($class) {
    $classDir = '/_class/';
    $classExt = '.php';
    include $_SERVER['DOCUMENT_ROOT'] . $classDir . $class . $classExt;
    });
    
    //Your code
        class bar {
            public function bar () {
                echo foo::something();
            }
        }
    

提交回复
热议问题