如何从C类访问$var,我尝试使用parent::p arent::$var但这不起作用。
<?php
class A {
protected static $var = null;
public function __construct(){
self::$var = "Hello";
}
}
class B extends A {
parent::__construct();
//without using an intermediate var. e.g: $this->var1 = parent::$var;
}
class C extends B {
//need to access $var from here.
}
?>
由于变量是静态的,您可以像下面这样访问变量 -
A::$var;
只要该属性未声明为私有,您就可以使用self::
.除私有属性以外的任何内容都可以从层次结构中的任何位置使用。
class A {
protected static $var = null;
public function __construct(){
self::$var = "Hello";
}
}
class B extends A {
}
class C extends B {
function get() { echo self::$var; }
}
(new C)->get();
你好
请参阅 https://eval.in/1022037