在PHP的子类中访问抽象类非静态变量

时间:2013-03-07 20:40:13

标签: php oop inheritance abstract-class abstract

我有一个抽象类,基本上它定义了一堆常量,变量,抽象方法和非抽象/常规方法。它的典型结构是这样的:

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,即子类如何访问抽象父类 * 成员变量 *?

2 个答案:

答案 0 :(得分: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() {}

答案 1 :(得分:2)

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'];
  }
}