PHP Classes and Objects
Accessing Overridden Methods
Problem
You want to access a method in the parent class that’s been overridden in the child.Solution
Prefix parent to the method name:class shape {
function draw() {
// write to screen
}
}
class circle extends shape {
function draw($origin, $radius) {
// validate data
if ($radius > 0) {
parent::draw();
return true;
}
return false;
}
}
Discussion
When you override a parent method by defining one in the child, the parent method isn’t called unless you explicitly reference it.In the Solution, we override the draw() method in the child class, circle, because we want to accept circle-specific parameters and validate the data. However, in this case, we still want to perform the generic shape::draw() action, which does the actual drawing, so we call parent::draw() inside our method if $radius is greater than 0.
Only code inside the class can use parent::. Calling parent::draw() from outside the class gets you a parse error. For example, if circle::draw() checked only the radius, but you also wanted to call shape::draw(), this wouldn’t work:2
$circle = new circle;
if ($circle->draw($origin, $radius)) {
$circle->parent::draw();
}
This also applies to object constructors, so it’s quite common to see the following:
class circle {
function __construct($x, $y, $r) {
// call shape's constructor first
parent::__construct();
// now do circle-specific stuff
}
}
No comments:
Post a Comment