johnlemon
johnlemon

Reputation: 21449

Strange working php code regarding protected visibility

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();

Why is this line working

$objF->blend = true;
instead of throwing a Fatal error ?

Upvotes: 2

Views: 97

Answers (3)

Charles
Charles

Reputation: 51411

The visibility modifiers work at the class level, not at the object level. This also means that objects of the same class can access each other's private bits.

An example at the PHP interactive prompt:

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

Upvotes: 2

sharpner
sharpner

Reputation: 3937

because you're accessing it from inside the class, if you would call from outside the class

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

it would throw a fatal error.

Upvotes: 0

Gaurav
Gaurav

Reputation: 28755

$objF is instance of class Fruit.

$objF->blend is being used in class itself. Protected properties can be used in class itself.

You will get Fatal Error if you use it outside the class as $fruit->blend;

So it is allowed to do so.

Upvotes: 1

Related Questions