PHP - 在 class 的构造函数中初始化对象实例,在静态成员中访问

PHP - Initialize instance of object within a constructor of a class, access within a static member

我正在使用一个框架将我的路由路由到控制器及其各自的方法,但是我不确定如何在构造函数中初始化 classes,然后通过同一个 class 的静态成员访问它 class.

class Controller {

    static private $test = null;

    private function __construct(){

        #$this->test = new Test();
        self::$test = new Test();

    }

    public static function Index(){

        // rather than this
        #$test = new Test();
        #echo $test->greet();

        // something like this
        #echo self::$test->greet();

    }

}

您必须先初始化控制器。您可以为此调用 new Controller();,然后将 Test 的实例放入 private $test

<?php
Class Test {

    public function greet(){
        return "hello world";   
    }

}

class Controller {

    static private $test = null;

    private function __construct(){

        self::$test = new Test();

    }

    public static function Index(){

        new Controller();
        echo self::$test->greet();

    }

}

Controller::Index(); //Returns hello world