Reputation: 10240
class Grandfather {
protected function stuff() {
// Code.
}
}
class Dad extends Grandfather {
function __construct() {
// I can refer to a member in the parent class easily.
parent::stuff();
}
}
class Kid extends Dad {
// How do I refer to the stuff() method which is inside the Grandfather class from here?
}
How can I refer to a member of the Grandfather class from within the Kid class?
My first thought was Classname::method()
but is there a keyword available such as self
or parent
?
Upvotes: 3
Views: 126
Reputation: 1976
stuff()
is nowhere overriden in the class hierarchy you can call the function with $this->stuff()
stuff()
were to be overriden in Dad
you have to call the function with the classname, e.g. Grandfather::stuff()
stuff()
is overriden in Kid
, you can do the call via parent::stuff()
Upvotes: 4
Reputation: 1283
$this->stuff()
or
Grandfather::stuff()
calling with this will call ::stuff()
method on the top of inherit level
(in your example it'd be Dad::stuff()
, but you don't override ::stuff
in Dad
class so it'd be Grandfather::stuff()
)
and Class::method()
will call exact class method
Example code:
<?php
class Grandfather {
protected function stuff() {
echo "Yeeeh";
// Code.
}
}
class Dad extends Grandfather {
function __construct() {
// I can refer to a member in the parent class easily.
parent::stuff();
}
}
class Kid extends Dad {
public function doThatStuff(){
Grandfather::stuff();
}
// How do I refer to the stuff() method which is inside the Grandfather class from here?
}
$Kid = new Kid();
$Kid->doThatStuff();
The "Yeeeh" will be outputted 2 times. Because constructor of Dad
(which is not overrided in Kid
class) class calls Grandfather::stuff()
and Kid::doThatStuff()
calls it too
Upvotes: 5
Reputation: 6204
If you want call Grandfather::stuff method you can do this using Grandfather::stuff()
in Kid
class.
Look at this example.
Upvotes: 1