Type hint for descendant classes

前端 未结 2 1875
梦如初夏
梦如初夏 2021-01-23 18:45

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 al

2条回答
  •  北海茫月
    2021-01-23 18:55

    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());
    

提交回复
热议问题