2017-10-14 66 views
-6
<?php 
    class Test 
    { 
     private $a = 10; 
     public $b ='abc'; 



} 
class Test2 extends Test 
{ 

    function __construct() 
    { 

     echo $this->a; 
     echo $this->a = 20; // wh 
    } 

} 
$test3 = new Test2(); 

回答

3
echo $this->a; 

呼應類屬性a的價值。此屬性是未定義,因爲類的屬性a私人,因此在類Test2中不可用。所以,產品a創建於Test2

echo $this->a = 20; // wh 

做下一:分配20到a屬性(其上一行創建)和回波分配是20的結果。

解決辦法:

class Test 
{ 
     // protected property is avalilable in child classes 
     protected $a = 10; 
     public $b ='abc'; 
} 

class Test2 extends Test 
{ 
    function __construct() 
    { 
     echo $this->a; 
     $this->a = 20; 
     echo $this->a; 
    } 
} 
$test3 = new Test2(); // outputs 10 20 
+1

的Bleh。我接近投票錯誤的原因。我應該欺騙了這個https://stackoverflow.com/questions/4361553/what-is-the-difference-between-public-private-and-protected – Machavity

+0

感謝您的幫助 –

-1

你應該改變

private $a = 10; 

到:

protected $a = 10; 
+0

當然,但問題是「爲什麼」 ?你可以從[u_mulder的回答](https://stackoverflow.com/a/46745074/1415724)瞭解一兩件事。 –

+0

謝謝walid ajaj –

相關問題