2011-03-24 51 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; 

称其将抛出一个致命的错误。