1

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

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

4

2 回答 2

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() {}
于 2013-03-07T20:43:10.290 回答
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'];
  }
}
于 2013-03-07T20:48:59.147 回答