4 ms·
Ask HN: PHP, interfaces, typehinting subtype and LSP?
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?
- FreezerburnV 13y agoThis is a question that would be better suited to asking on stackoverflow.com
- jaachan 13y agoIt 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 13y agoBased 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 13y agoSay 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