PHP Overriding Methods
What
To create a child class whose methods are different from the corresponding methods in the parent class by overriding a parent class's method in the child class.
How
To do this, simply create a method with the same name in the child class. Then, when that method name is called for an object of the child class, the child class's method is run instead of the parent class's method:
<?PHP// ww w . j av a 2s.co m
class ParentClass {
public function someMethod() {
// (do stuff here)
}
}
class ChildClass extends ParentClass {
public function someMethod() {
// This method is called instead for ChildClass objects
}
}
$parentObj = new ParentClass;
$parentObj->someMethod(); // Calls ParentClass::someMethod()
$childObj = new ChildClass;
$childObj->someMethod(); // Calls ChildClass::someMethod()
?>
Example
PHP allows us to redefine methods in subclasses. This is done by redefining the method inside the child class:
<?PHP/* w w w. j a v a 2s . c o m*/
class Dog {
public function bark() {
print "Dog";
}
}
class Puppy extends Dog {
public function bark() {
print "Puppy";
}
}
?>
Preserving the Functionality of the Parent Class
To call an overridden method, you write parent:: before the method name:
parent::someMethod();
<?php /* w w w . j av a2 s . co m*/
class Fruit {
public function peel() {
echo "peeling the fruit.\n";
}
public function slice() {
echo "slicing the fruit.\n";
}
public function eat() {
echo "eating the fruit. \n";
}
public function consume() {
$this-> peel();
$this-> slice();
$this-> eat();
}
}
class Banana extends Fruit {
public function consume() {
echo " < p > I'm breaking off a banana... < /p > ";
parent::consume();
}
}
$apple = new Fruit;
$apple->consume();
$banana = new Banana;
$banana->consume();
?>
The code above generates the following result.