Hacker News new | past | comments | ask | show | jobs | submit login
Ask HN: PHP, interfaces, typehinting subtype and LSP?
2 points by enterx on Dec 2, 2013 | hide | past | favorite | 6 comments
interface I

{

function foo(stdClass $arg);

}

class Test extends stdClass

{

}

class Implementation implements I

{

function foo(Test $arg)

{

}

}

Result:

Fatal error: Declaration of InterfaceImplementation::foo() must be compatible with I::foo(stdClass $arg) in test.php on line XY

How come that I can't type hint a subtype in the implementation?




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.


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.


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


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


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


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




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: