Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip execution of a parent method to execute grandparent method? [duplicate]

Tags:

php

Possible Duplicate:
How do I get a PHP class constructor to call its parent's parent's constructor

I know this sounds strange, but I am trying to get around a bug. How can I call a grandparent method?

<?php
class Person {
    function speak(){ echo 'person'; }
}
class Child extends Person {
    function speak(){ echo 'child'; }
}
class GrandChild extends Child {
    function speak(){
      //skip parent, in order to call grandparent speak method
    }
}
like image 667
Andrew Avatar asked Sep 25 '12 18:09

Andrew


2 Answers

PHP has native way to do this.

try this:

class Person {

    function speak(){ 

        echo 'person'; 
    }
}

class Child extends Person {

    function speak(){

        echo 'child';
    }
}

class GrandChild extends Child {

    function speak() {

         // Now here php allow you to call a parents method using this way.
         // This is not a bug. I know it would make you think on a static methid, but 
         // notice that the function speak in the class Person is not a static function.

         Person::speak();

    }
}

$grandchild_object = new GrandChild();

$grandchild_object->speak();
like image 96
slash28cu Avatar answered Nov 13 '22 20:11

slash28cu


You can just call it explicitly;

class GrandChild extends Child {
    function speak() {
       Person::speak();
    }
}

parent is just a way to use the closest base class without using the base class name in more than one place, but giving any base class' class name works just as well to use that instead of the immediate parent.

like image 39
Joachim Isaksson Avatar answered Nov 13 '22 22:11

Joachim Isaksson