The result of this example is " Class A! ", not " Class B! ", why ?
class A {
private function foo() {
echo "Class A ! n";
}
public function test() {
var_dump($this);
$this->foo();
}
}
class B extends A {
public function foo() {
echo "Class B ! n";
}
}
$b = new B();
$b->test();
// Outputs:
// object(B)#1 (0) {}
// Class A !
I thought the result is " Class B! "
3
Answers
Private classes cannot be modified in the child class
change code to this and work:
The reason is because
test()
function inside classAA
calls$this->foo()
which means the it’s the function within the class(AA
) itself andAA->foo()
is a private function . Plus$this
is a special variable in PHP that refers to current object. When the classes are inheriting seefoo()
of classBB
andCC
access modifiers arepublic
butAA->foo()
isprivate
. In order to override a function you need to have the same access modifiers. Since the access modifiers are not the same even though the names are similarAA->foo()
not be overridden.Because
foo()
isprivate
in class A it is not visible outside that class. Thereforefoo()
in class B is treated as a different function.foo()
in B doesn’t overridefoo()
in A. And sincetest()
is part of A, it uses the function from A with that name.If you make both functions public, you get the behaviour you were expecting – demo: https://3v4l.org/8kOCl.