Php type hinting not getting along with interfaces and abstract classes?

后端 未结 3 1503
[愿得一人]
[愿得一人] 2020-12-01 18:08

I think it\'ll be much easier to see the problem in a code example than writing the question in the first place. Here is my php code:



        
相关标签:
3条回答
  • 2020-12-01 18:37

    Does not compute. We had the same discussion yesterday:
    Can parameter types be specialized in PHP

    All your derived classes must implement the method signatures identically.

    This is something that would ideally be checked at runtime. But in PHP the parser does. (To compensate, PHP does not check private/protected attribute access at parsing time, but let that one rather blow up at runtime.)

    If you want to enforce a more stringent type, I would advise:

     assert( is_a($Object, "AClass") );
    
    0 讨论(0)
  • 2020-12-01 18:58

    Here's an example that shows, why this is not allowed:

    <?php
    class BClass implements AnInterface { }
    
    function moo(AnAbstractClass $abstract)
    {
        $b = new BClass();
        $abstract->method($b);
    }
    

    This would be a valid code, but it would fail, if you pass a ConcreteClass to moo, because its method ConcreteClass::method does not allow BClass.

    It is complicated, but it is easier to understand, if you see an example.

    0 讨论(0)
  • 2020-12-01 19:02

    php doesn't seem to be recognizing the signatures of AnAbstractClass::method and ConcreteClass::method as compatible.

    PHP is correct, they're not compatible. By allowing only instances of AClass (or its children) to be passed to ConcreteClass::method, you're breaking the contract that AnAbstractClass provides: Any of its subclasses must accept AnInterface as an argument to its method().

    If your example worked, and I had another class BClass implementing AnInterface, we'd have a situation where according to AnAbstractClass, method() should accept instances of BClass, while according to ConcreteClass, it shouldn't.

    Change your signature for ConcreteClass::method to match that of AnAbstractClass::method.

    0 讨论(0)
提交回复
热议问题