phpoopinterfaceextending-classes

PHP child class cannot implement same interface parent class implements


Is it normal behavior that child class cannot implement same interface parent class implements? I got PHP v5.6

interface blueprint {
    public function implement_me();
}

class one implements blueprint {

    public function implement_me() {

    }

}

class two extends one implements blueprint {


}

//no fatal error triggered for class two 

EDIT: So above code works great no errors or warnings even though i implemented interface blueprint in child class two without having method impement_me() why child class cannot implement same interface parent class implements?

if i implement another interface other than blueprint for class two then it works and i have to use blueprint_new methods inside class two otherwise fatal error triggered. This part works as intended.

interface blueprint {
    public function implement_me();
}

class one implements blueprint {

    public function implement_me() {

    }

}


interface blueprint_new {
    public function todo();
}


class two extends one implements blueprint_new {


}

//this will trigger fatal error.

Solution

  • The child class automatically inherits all interfaces from the parent class.

    Sometimes you don't want this but you still can implement any, even multiple interfaces in the child class.

    The only thing that does not work is to extend an interface, just like a class (or an abstract class) cannot be implemented.

    The error triggered in your second code is because you didn't implement all methods from interface blueprint_new in class two, but basically there is nothing wrong in your code.

    Example:

    class MobilePhone implements GsmSignalPowered {}
    class SamsungGalaxy extends MobilePhone implements UsbConnection {}
    interface ThunderboltPowered {}
    interface GsmSignalPowered {}
    interface UsbConnection {}
    
    $s = new SamsungGalaxy();
    var_dump($s instanceof GsmSignalPowered); // true
    var_dump($s instanceof UsbConnection); // true
    var_dump($s instanceof ThunderboltPowered); // false
    
    $m = new MobilePhone();
    var_dump($m instanceof GsmSignalPowered); // true
    var_dump($m instanceof UsbConnection); // false
    var_dump($m instanceof ThunderboltPowered); // false