[英]PHP - Initialize instance of object within a constructor of a class, access within a static member
我正在使用一个框架将路由路由到控制器及其各自的方法,但是我不确定如何在构造函数中初始化类,然后通过同一类的静态成员进行访问。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.