interface A
{
public function method1();
public function method2();
}
abstract class B implements A
{
public $publicc = 2;
public function method1()
{
echo "in method1 of B<br>";
}
}
class C extends B
{
public $publicc = 4;
public function __construct()
{
}
public function method2()
{
}
public function method1()
{
echo $this->publicc + parent::$publicc; // error for using parent::$publicc
}
}
$obj = new C();
$obj->method1();
但是php抛出错误echo $ this-&gt; publicc + parent :: $ publicc。我只想直接得到父类$ publicc属性,其值为2,不使用任何存取方法。有没有办法在PHP中执行此操作?
答案 0 :(得分:0)
这取决于publicc究竟持有什么,但是常数可能适合您的需求?
interface A
{
public function method1();
public function method2();
}
abstract class B implements A
{
const PUBLICC = 2;
public function method1()
{
echo "in method1 of B<br>";
}
}
class C extends B
{
const PUBLICC = 4;
public function __construct()
{
}
public function method2()
{
}
public function method1()
{
echo self::PUBLICC + parent::PUBLICC; // error for using parent::PUBLICC
}
}
$obj = new C();
$obj->method1();
答案 1 :(得分:0)
我认为你想要一个静态属性。如果它是您想要在没有实例的情况下访问的属性,则通常表示静态变量的候选者。
abstract class B implements A
{
protected static $publicc = 2;
...
}
class C extends B
{
public $publicc = 4;
public function __construct()
{
}
public function method2()
{
}
public function method1()
{
echo $this->publicc + parent::$publicc; // error for using parent::$publicc
}
}