Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Parent Function with the Same Signature/Name

A and B have function with the same signature -- let's assume : foo($arg) -- and that class A extends B.

Now I have an instance:

$a = new A();

$a.foo($data);

Can I also run the parent's (B's) foo() function through $a or was it overridden?

Thanks! Nimi

like image 203
Nimi Avatar asked Nov 16 '11 08:11

Nimi


People also ask

How to call a function of a parent class from a child?

You just have to create an object of the child class and call the function of the parent class using dot (.) operator.

How do you call a parent class from a super class?

Using Classname: Parent’s class methods can be called by using the Parent classname.method inside the overridden method. Using Super (): Python super () function provides us the facility to refer to the parent class explicitly. It is basically useful where we have to call superclass functions.

How to call parent class methods from parent class in Python?

Using Classname: Parent’s class methods can be called by using the Parent classname.method inside the overridden method. Using Super (): Python super () function provides us the facility to refer to the parent class explicitly.

Which function is called by the parent class P1?

The parent class p1 function is called. In the above program, a parent class p1 is created and a function first () is defined in it. class p1 { public: void first () { cout << " The parent class p1 function is called."; } }; A derived class is created, which is inheriting parent class p1 and overloading the parent class function first ().


2 Answers

It is overridden but if you want to use both you can do this:

function parentFoo($arg)
{
    return parent::foo($arg);
}

If you want that the child function calls the parent function do this:

function foo($arg)
{
    $result = parent::foo($arg);
    // Do whatever you want
}

See this URL for more information: http://php.net/manual/en/keyword.parent.php

like image 199
Niels Avatar answered Sep 24 '22 18:09

Niels


. is the string concatenation operator in PHP. To call methods, use ->.

To call an overridden method, use parent::method()

class B {
  public function foo($data) {
    echo 'B';
  }
}

class A extends B{
  public function foo($data) {
    parent::foo($data);
    echo 'A';
  }
}

$a = new A();
$a->foo($data); // BA
$b = new B();
$b->foo($data); // B
like image 28
knittl Avatar answered Sep 24 '22 18:09

knittl