Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling an overridden parent method

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(); 
like image 498
kiler129 Avatar asked Nov 10 '11 00:11

kiler129


People also ask

How do you invoke an overridden superclass method from a subclass?

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.

How do you call a method overridden in Python?

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.


1 Answers

Use parent:: before method name, e.g.

parent::test(); 

See parent

like image 126
Adam Zalcman Avatar answered Sep 23 '22 04:09

Adam Zalcman