2014-09-25 46 views
-1

我有兩個類,每個類都有不同的文件。 我試圖訪問變量$this->_myvalue頭等艙類二最初定義,但與錯誤消息不是成功使用$這個時候不是在對象上下文 有人能告訴我怎麼沒能得到Class Second的$this->_value如何從最初在超類中聲明的類中獲取變量?

//File First.php 
Class First extends Second{ 

    function some_function(){ 
     new Second($this->_myvalue); //Using $this when not in object context 
    } 
} 

//File Second.php 
Class Second extends Third{ 
    public $myvalue; 
    public function __construct($myvalue = null) { 
     $this->_myvalue = $myvalue; 
    } 
} 
+3

爲什麼你實例化擴展第二類中二的新實例?這表明對OOP繼承的理解不夠 – 2014-09-25 15:16:20

回答

1

它看起來像你誤解繼承:

class Parent 
{ 
    public $val; 

    public function __construct($val = null) { 
     $this->val = $val; 
    } 
} 

class Child extends Parent 
{ 
    public function something() { 
     echo $this->val; 
    } 
} 

你現在可以做

$parent = new Parent(5); 
echo $parent->val; // 5 

$child = new Child(10); // __construct is inherited from Parent 
echo $child->val; // 10 - public $val is also inherited 
$child->something(); // 10