7.7. 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 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:[4]

$circle = new circle;
if ($circle->draw($origin, $radius)) {
    $circle->parent::draw();
}

If you want to call the constructor belonging to an object’s parent but don’t know the parent’s class name, use get_parent_class( ) to dynamically identify the parent, then combine that with parent:: to call the parent’s constructor:

class circle extends shape { function circle( ) { $parent = get_parent_class($this); ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.