In the sample code below, the method test()
in parent class Foo
is overridden by the method test()
in child class Bar
. Is it possible to call Foo::test()
from Bar::test()
?
class Foo { $text = "world\n"; protected function test() { echo $this->text; } }// class Foo class Bar extends Foo { public function test() { echo "Hello, "; // Cannot use 'parent::test()' because, in this case, // Foo::test() requires object data from $this parent::test(); } }// class Bar extends Foo $x = new Bar; $x->test();
The overridden method shall not be accessible from outside of the classes at all. But you can call it within the child class itself. to call a super class method from within a sub class you can use the super keyword.
In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.
Use parent::
before method name, e.g.
parent::test();
See parent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With