PHP Cookbook: Solutions and Examples for PHP Programmers

7.14.1. Problem

You want to access a method in the parent class that's been overridden in the child.

7.14.2. 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; } }

7.14.3. 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 you 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 your 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:[]

[] In fact, it fails with the error unexpected T_PAAMAYIM_NEKUDOTAYIM, which is Hebrew for "double-colon."

$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 } }

The simplicity of invoking a parent constructor is one advantage of PHP 5's consistent naming scheme for constructors, as you need to jump through all sorts of hoops to implement this in PHP 4 in a non-brittle way.fs

7.14.4. See Also

Recipe 7.2 for more on object constructors; documentation on class parents at http://www.php.net/keyword.parent and on get_parent_class( ) at http://www.php.net/get-parent-class.

Категории