2011-07-20 78 views
1
<?php 
class Example{ 
public $pub="public"; 
private $priv = "private"; 
protected $prot = "protected"; 
} 
class SubClass extends Example{ 
} 
$ex = new Example(); 
$sub = new SubClass(); 
/* called indiviually */ 
echo $sub->priv; // error 
echo $sub->prot; // error 

echo "<br/>"; 

echo $ex->pub; // works 
echo $ex->prot; // error 
?> 

正如你可以看到調用保護的變量,無論是父類或子類拋出錯誤。那麼我可以假設的是:這樣做,$ PROT的行爲就像在父類private修飾符,我們不允許從類塊外調用它。$ PROT變量時繼承到子類,它開始表現得像私有變量,因爲即使現在,它是不允許從外部調用它。 PS:沒研究::範圍解析操作符呢。只用 - >箭頭,$這是否受保護的變量在繼承的類變成私有?

回答

0

受保護的變量可以在子類中,但將在其他範圍內引發錯誤:

<?php 
class Example{ 
     public $pub="public"; 
     private $priv = "private"; 
     protected $prot = "protected"; 
} 
class SubClass extends Example{ 
     function get_protected() { 
      return $this->prot; 
     } 
} 

$ex = new Example(); 
$sub = new SubClass(); 

/* called indiviually */ 
echo $sub->priv; // error 
echo $sub->prot; // error 

echo $sub->get_protected() // works 

echo $ex->pub; // works 
echo $ex->prot; // error 
相關問題