As of PHP 7.2 we can finally return type declarations for the object data type.
(I know that reads funny, but it’s a true statement!)
Here is an example:
1
2
3
4
5
6
7
8
9
10
11
| class MyClass {
public $var = 'Hello World';
}
$myclass = new MyClass;
function getTestType(MyClass $arg) : object {
return $arg;
}
echo getTestType($myclass)->var;
|
Previous PHP versions would shit their pants over this with a fatal error:
1
| Fatal error: Uncaught TypeError: Return value of test() must be an instance of object, instance of MyClass returned in app/index.php:10
|
Now, of course, we get “Hello World!”