2013-03-07 87 views
1

我有一個抽象類,它基本上定義了一堆常量,變量,抽象方法和非抽象/常規方法。這是典型的結構是這樣的:在PHP的子類中訪問抽象類非靜態變量

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

您有三個錯誤。這裏有一個工作示例。看代碼註釋

// |------- 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

哇靠!所以簡單...有時候我忘記了最基本的東西......老太太變老了......謝謝! :) – 2013-03-07 20:50:31

+0

:)不客氣 – hek2mgl 2013-03-07 20:51:18

+0

等待'必須實施,因爲它是在父類中聲明爲抽象',但跳過它,可能應該更清楚,我正在尋找的是訪問$ variable_2,謝謝 – 2013-03-07 20:52:11

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