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

时间:2016-04-14 08:09:28

标签: php controller static-methods

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

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();

    }

}

1 个答案:

答案 0 :(得分:2)

您必须先初始化控制器。您可以为此调用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