self and parent in PHP5
self
Using self you can call a function inside particular class.
Parent
Using parent you call a function in the parent of the class.
So basic usage for self and parent is you can call a function which is overrided by the child class.
Example:
class animal{
public function function2(){
echo “function two in parent class”;
}
public function function3(){
echo “function three in parent class”;
$this->function2();
self::function2();
}
}
class Lion extends animal{
public function function1(){
echo “function one in child class”;
self::function2();
parent::function2();
$this->function3();
}
public function function2(){
echo “function two in child class”;
}
}
In the above example
Under function3() in Lion class.
self::function2()
This will call the function2 in Lion class.
parent::function2()
- This will call the function2 in animal class.
- So here function2() is already overrided by the Lion class, using parent:: now we can call the function of parent class
Under function3() in animal class.
$this->function2()
- It will call the function2() in the Lion class. Not in the animal class.
self::function2()
- It will call the function2() in the animal class.
- So using self:: we can call the function which is overrided by the child class
