我有一个抽象类,基本上它定义了一堆常量,变量,抽象方法和非抽象/常规方法。它的典型结构是这样的:
abstract class ClassName{
const CONSTANT_NAME = "test";
protected static $variable_1 = "value";
protected $variable_2 = "value_2";
protected $variable_3 = "value_3"
abstract function doSomething();
protected function doSomethingElse();
}
当我扩展这个类,并且需要访问子类中受保护的变量时,例如:
public class ChildClassName extends ClassName{
public function accessParentClassMembers()
{
echo parent::$variable_1; // WORKS FINE
echo parent::$variable_2; // OBVIOUSLY DOESN'T WORK because it is not a static variable
}
}
问题是,我如何访问$variable_2,那就是子类如何访问抽象父类 *成员变量*?
你有三个错误。下面是一个工作示例。参见代码注释
// |------- public is not allowed for classes in php
// |
/* public */ class ChildClassName extends ClassName{
// has to be implemented as it is declared abstract in parent class
protected function doSomething() {
}
public function accessParentClassMembers() {
// note that the following two lines follow the same terminology as
// if the base class where non abstract
// ok, as $variable_1 is static
echo parent::$variable_1;
// use this-> instead of parent::
// for non static instance members
echo $this->variable_2;
}
}
进一步注意,这:
protected function doSomethingElse();
在父类中不起作用。这是因为所有非抽象方法都必须有一个主体。所以你有两个选择:
abstract protected function doSomethingElse();
或
protected function doSomethingElse() {}
abstract class ClassName{
protected static $variable_1 = "value";
protected $variable_2 = "value_2";
protected $variable_3 = "value_3";
}
class ChildClassName extends ClassName{
protected $variable_3 = 'other_variable';
public function accessParentClassMembers()
{
echo parent::$variable_1;
echo $this->variable_2;
echo $this->variable_3;
$parentprops = get_class_vars(get_parent_class($this));
echo $parentprops['variable_3'];
}
}