Consider the following snippet:
Class A {
private $a = \'foo\';
public function F() {
return $this->a;
}
}
Class B extends A {
From PHP: Visibility:
Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.
In your example, regardless of the object being of class B
, class A
cannot access a private
property of another class.
Also, if B
has a protected property, that cannot override the class A
property because it is private
.
Both your example and the following yield foo
:
Class A {
private $a = 'foo';
public function F() {
return $this->a;
}
}
Class B extends A {
protected $a = 'bar';
public function F() {
return parent::F();
}
}
echo (new B)->F();
However, if class A
is also protected
then it can be overridden by class B
and class A
has access to the property in class B
.
Yields bar
:
Class A {
protected $a = 'foo';
public function F() {
return $this->a;
}
}
Class B extends A {
protected $a = 'bar';
public function F() {
return parent::F();
}
}
echo (new B)->F();