user1861171
user1861171

Reputation: 21

Why I can access private property in parent php class?

We recently found this strange PHP behaviour. Accessing a private in the parent class should not work. Is this a feature? Maybe someone can explain it.

// PHP classes

class Father {
    // private property
    private $value = 'test';
}

Class Child extends Father {

    // Should fail, se
    public function setValue() {
     $this->value = 'why does';
    }

    public function getValue() {
     return $this->value;
    }
}


$c = new Child();

// should fail!
$c->setValue();
echo $c->getValue() . "|";

// should fail!!!!!!!
$c->value = "it work?";
echo $c->getValue();

// output: why does|it work?

Upvotes: 2

Views: 622

Answers (1)

David Müller
David Müller

Reputation: 5351

You are not changing the Father's private property, but introducing a new property value for the child.

Upvotes: 6

Related Questions