Type hint for descendant classes

谁说胖子不能爱 提交于 2020-01-11 12:26:53

问题


From the docs page http://php.net/manual/en/language.oop5.typehinting.php

If class or interface is specified as type hint then all its children or implementations are allowed too.

But:

class PimpleChild extends Pimple {
//...
}
interface Pimple_Config {
    public function configure(Pimple $container);
}
class PimpleConfigurer_Factories implements Pimple_Config {
    public function configure(PimpleChild $container) {
    //...
    }
}

returns fatal error. Why?


回答1:


If I am not mistaken you get this error:

Declaration of PimpleConfigurer_Factories::configure() must be compatible with Pimple_Config::configure(Pimple $container) ...

Which means: If you define a method in a super class or in an interface, all sub classes (or classes implementing the interface) must use exactly this definition. You cannot use another type here.

As for your quote from the documentation:

If class or interface is specified as type hint then all its children or implementations are allowed too.

This only means that you can pass a variable which is of a certain type or all its children.

For example: Say you have the following classes:

class Car {
    protected $hp = 50;
    public function getHp() { return $this->hp; }
}

class SuperCar extends Car {
    protected $hp = 700;
}

And a function (or method, no difference there) with type hint:

function showHorsePower(Car $car) {
    echo $car->getHp();
}

You can now pass all objects of type Car and all its sub classes (here SuperCar) to this function, like:

showHorsePower(new Car());
showHorsePower(new SuperCar());



回答2:


From the same typehinting section you linked to:

The class implementing the interface must use the exact same method signatures as are defined in the interface. Not doing so will result in a fatal error.

For the method signatures to be the same, they must contain the exact same typehints. And also relevant because it is similar...

From the OOP Basics - extends section of the manual:

When overriding methods, the parameter signature should remain the same or PHP will generate an E_STRICT level error. This does not apply to the constructor, which allows overriding with different parameters.



来源:https://stackoverflow.com/questions/28217727/type-hint-for-descendant-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!