假设我有两个类:SuperObject和PageGenerator。
PageGenerator(和许多其他类)继承SuperObject,SuperObject有一个名为“db_conn”的字段用于数据库连接。
所以我的代码看起来像:
class SuperObject {
protected static $db_conn = null;
public function __construct($db){ $this->db_conn = $db; }
}
class PageGenerator extends SuperObject {
public function some_function(){
//something using parent::$db_conn;
}
}
// somewhere down the way
$so = new SuperObject( $db_object );
$page = new PageGenerator();
$page->some_function();
但我认为我不能这样做,至少,不是那样。
那又怎么样?
答案 0 :(得分:0)
您可以使用父保护静态字段:
public function some_function(){
var_dump(self::$db_conn); //not parent::$db_conn;
}
但是你没有在SuperObject中正确地初始化它。将
class SuperObject {
protected static $db_conn = null;
public function __construct($db){ self::$db_conn = $db; }
}
答案 1 :(得分:0)
class SuperObject {
protected static $db_conn = null;
public function __construct($db){ self::$db_conn = $db; }
}
class PageGenerator extends SuperObject {
public function some_function(){
var_dump(self::$db_conn);
}
}
// somewhere down the way
$page = new PageGenerator( new \stdClass() );
$page->some_function();