As some of you know, I’ve been working for a while on implementing type hinting for method return values. I’m pleased to say that the implementation is done.
The following types are allowed:
- Array
- Class names
Parameter type hints allow callable types, but until a keyword is assigned to “callable” (RFC), it’s not possible to implement this for method returns. To be honest, I’m not completely sold that it should be implemented at all. That’s another conversation.
The syntax is simple – rather than declaring “function”, you replace it with array or your class name. Since mixed types are allowed, you can still use “function”.
<?php class MyClass { public ArrayIterator getIterator() { return new ArrayIterator(); } public array getArray() { return array('I am returning an array'); } public function thisStillWorks() { return 'This still works, too.'; } }
The same rules and errors for type hint parameters apply if you attempt to return a value not specified by the return type; a catchable fatal error will be thrown. Note that this is NOT an exception.
Reflection
I added “getReturnType()” to the ReflectionMethod class. It will return one of these three values: “mixed” – for function, “array” or “ClassName” if an object is specified.
Interfaces
Interface implementation is incomplete. I will be working on that this week. That said, if you specify an interface on the return type, it works just fine. The only thing not implemented is validation on overloading interface methods.
Interfaces and type hinting return values are fully implemented now. If, for example, you implement an interface which defines a method that returns an array, and you attempt to change it, an E_COMPILE_ERROR is raised.
<?php interface MyInterface { public function blah(); } class YourClass implements MyInterface { public function blah() { return 'works!'; } } class MyClass { public MyInterface getValue() { return new YourClass(); } }
The above works and validates correctly.
Help
If you’re interested in testing out this patch, shoot me an email using the contact page. If you’d just like to play with the functionality, go to my GutHub page and download or clone the repo. The branch I’m working out of is “returntype”. Just make sure you compile with –enable-debug.
If you happen to run into any memory leaks, please provide any information returned from the output.
Until next time.












Leave a Reply