rfc:returntypehint
Request for Comments: Return type-hint
- Version: 1.0
- Date: 2010-07-28
- Author: Felipe Pena felipe@php.net
- Status: Under Discussion
- First Published at: http://wiki.php.net/rfc/typehint
Introduction
The purpose of the RFC is to discuss about the return type hint utility on PHP.
Differences from the old proposal
- The old proposal (return and param type-hint) was introducing some keywords (the type names), with this new proposal there is no such BC.
- The new proposal has a better error message, identifying where the function/method was called.
- Added generic “numeric”, “scalar” types
- No needed strange syntax to solve parser conflicts
Examples
Using "scalar" type-hint
<?php function scalar abc($x = NULL) { return $x; } var_dump(abc(1)); // int(1) var_dump(abc(1.)); // float(1) var_dump(abc()); /* PHP Catchable fatal error: The returned value must be of the type scalar, called in ... on line 9 and returning in ... on line 4 */
Using an user class type
<?php class Bar { } class Foo extends Bar { public function Bar test($x) { return $x; } } $foo = new Foo; $foo->test($foo); // ok $foo->test(new stdClass); // fail /* PHP Catchable fatal error: The returned value should be instance of Bar, called in ... on line 13 and returning in ... on line 7 */
Interface defining the return type-hint
<?php interface ITest { function string bar(); } class Foo implements ITest { public function int bar() { } } // PHP Fatal error: Declaration of Foo::bar() must be compatible with that of ITest::bar() in ... on line 7
Using a namespaced class
<?php namespace foo { class foo { } class bar extends foo { } } namespace bar { class bar { public function \foo\foo test() { return new \foo\bar; } } $bar = new bar; $bar->test(); // ok }
Reflection
- See below some information that will be possible to be get using Reflection.
Using a class type
<?php interface Test { } class foo implements Test { function Test test() { return new foo; } } $func = new ReflectionMethod('foo::test'); var_dump($func->getReturnTypeHint()); // "Test" var_dump($func->returnsObject()); // true
PHP native types
<?php function scalar abc($x = NULL) { return $x; } $func = new ReflectionFunction('abc'); var_dump($func->getReturnTypeHint()); // scalar var_dump($func->returnsScalar()); // true
Using "self" as type
<?php class foo { function self bar() { return new foo; } } $func = new ReflectionMethod('foo::bar'); var_dump($func->getReturnTypeHint()); // foo var_dump($func->returnsObject()); // true
Patch
- Engine + Reflection: http://felipe.ath.cx/diff/returntypehint.diff
rfc/returntypehint.txt · Last modified: 2017/09/22 13:28 by 127.0.0.1