

Ask HN: PHP, interfaces, typehinting subtype and LSP? - enterx

interface I<p>{<p>function foo(stdClass $arg);<p>}<p>class Test extends stdClass<p>{<p>}<p>class Implementation implements I<p>{<p>function foo(Test $arg)<p>{<p>}<p>}<p>Result:<p>Fatal error: Declaration of InterfaceImplementation::foo() must be compatible with I::foo(stdClass $arg) in test.php on line XY<p>How come that I can&#x27;t type hint a subtype in the implementation?
======
jaachan
It has to work with all subtypes of stdClass, since in order for the interface
to hold its word, I need to be able to get an object thats implements I, and
pass it any stdClass, regardless of what they do with it.

~~~
enterx
Based on the research I've made it is legal by the OO principles and SHOULD
work but it got omitted somehow in the trade-off during the implementation.

Also NOT available in java.lang.

~~~
jaachan
Say I have a function that accepts I as argument:

    
    
      function my_func(I $x)
      {
         $x->foo(new stdClass);
      }
    

That wouldn't be allowed, since your code requires an instance of Test, not
stdClass

------
FreezerburnV
This is a question that would be better suited to asking on stackoverflow.com

~~~
enterx
wow. you too might think of allocating unnecessary memory, wasting people's
bandwidth and occupying cognitive resources of others for nothing. TIA.

~~~
jaachan
It's true though, stack overflow gets you more programmer eyeballs

