2011-03-24 28 views
2
 
class Fruit { 
    protected $blend; 

    public function WillItBlend() { 
     return $this->blend; 
    } 
    public static function MakeFruit() { 
     $objF = new Fruit(); 
     $objF->blend = true; 
     return $objF; 
    } 
} 

$fruit = Fruit::MakeFruit(); 
echo $fruit->WillItBlend(); 

爲什麼這條線路工作奇怪的工作php代碼有關保護知名度

$objF->blend = true;
,而不是拋出致命錯誤?

+1

+1讓我想冰沙。 – Charles 2011-03-24 07:33:37

回答

2

可見性修飾符在類級而非對象級工作。這也意味着同一個類的對象可以訪問彼此的私有位。

在PHP交互提示一個例子:

php > class Foo { 
     private $bar; 
     public function __construct() { $this->bar = rand(1, 100); } 
     public function baz($another_foo) { echo $another_foo->bar, '-', $this->bar; } 
    } 
php > $a = new Foo(); 
php > $b = new Foo(); 
php > $a->baz($b); 
86-70 
1

$objF是類Fruit的實例。

$objF->blend正在課堂上使用。 Protected屬性可以在課堂上使用。

如果你使用它的類之外的$fruit->blend;

所以它是允許這樣做你會得到致命錯誤。

0

,因爲你從類內部訪問它,如果你想從外部類

$fruit = Fruit::MakeFruit(); 
echo $fruit->WillItBlend(); 
echo $fruit->blend; 

稱其將拋出一個致命的錯誤。