我使用框架将路由路由到控制器及其各自的方法,但是我不知道如何在构造函数中初始化类,然后通过同一类的静态成员访问它。
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();
}
}
答案 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