Reputation: 599
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
Upvotes: 9
Views: 8997
Reputation: 265341
.
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
Upvotes: 7
Reputation: 6106
In answer to your question, no, you can't call the parent's foo() method through an object of class A as the only foo() method the object A understands in its public API is its own foo() method. You probably need to think about your design. If B's foo() is providing different functionality to A's foo() then should one override the other? Or you need to think about A's foo() calling B's foo() via parent::foo() - assuming you want B's foo() called every time A's foo() is called. Or use another pattern. If A's foo() isn't always appropriate for an object of A then you might want to look at the Decorator or Strategy patttern's.
If you're starting out with OO programming I can't recommend the Gang of Four book highly enough.
Upvotes: 1
Reputation: 18859
Can I also run the parent's foo() function through $a or it was override ?
Not from the "outside". Say:
<?php
class A {
function talk( ) {
return 'Hello world';
}
}
class B extends A {
function talk( ) {
return 'Goodbye world';
}
}
$b = new B;
$b->talk( ); // Goodbye world.
In this example, it's not possible to have $b->talk output A::talk( ), other than proxying that through B. If you need to have the result from A instead of B, you might want to explain your dilemma; that's a problem you shouldn't run into, and if you do, the chances are the design isn't optimal.
Upvotes: 0
Reputation: 2142
In class A you can write
parent::foo($param);
to call the base classes foo(...) method.
Upvotes: 0
Reputation: 49929
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
Upvotes: 15