rfc:typehint
This is an old revision of the document!
Request for Comments: Return value and parameter type hint
- Version: 1.0
- Date: 2008-04-07
- Author: Felipe Pena felipensp@gmail.com
- Status: Under Discussion
BC Break
New tokens (new keywords)
- T_INTEGER (Keywords: int, integer)
- T_BOOLEAN (Keywords: bool, boolean)
- T_DOUBLE (Keywords: real, float, double)
- T_OBJECT (Keyword: object)
- T_RESOURCE (Keyword: resource)
- T_STR (Keyword: string)
Return value type hint - Examples
Using inside namespaces
namespace foo; class test { } class bar { static public function (foo::test) testing($instance) { return $instance; } } bar::testing(new test); bar::testing(new stdClass); // Catchable fatal error: The returned value should be instance of foo::test
Using inheritance
interface ITest { } class bar implements ITest { } class foo extends bar { } function (Itest) testing($instance) { return $instance; } testing(new bar); testing(new foo); testing(new stdClass); // Catchable fatal error: The returned value must implement interface Itest
PHP types
function (int) test($value) { return $value; } test('1337'); test(-1); test(1); test(1.); // Catchable fatal error: The returned value needs be integer
Parameter type hint - Examples
integer / int
function test(integer $value) { } test(1); test("1337"); test(-1); test("1."); // Catchable fatal error: Argument 1 passed to test() must be an integer, string given function test(integer $value = '1') { } // Fatal error: Default value for parameters with integer type hint can only be the exact type or NULL
double / float / real
function test(double $value) { } test(1.1); test(.1); test("1."); test("1337"); // Catchable fatal error: Argument 1 passed to test() must be an double, string given function test(double $value = '1') { } // Fatal error: Default value for parameters with double type hint can only be the exact type or NULL
bool / boolean
function test(bool $value = true) { } test(false); test(0); test(1); test('0'); test('1'); test(''); test(null); // Catchable fatal error: Argument 1 passed to test() must be an boolean, null given
resource
function test(resource $value) { } test(fopen(__FILE__, 'r')); test(NULL); // Catchable fatal error: Argument 1 passed to test() must be an resource, null given
object
function test(object $value) { } test(new stdclass); test(NULL); // Catchable fatal error: Argument 1 passed to test() must be an object, null given function test(object $value = 1) { } // Fatal error: Default value for parameters with object type hint can only be the exact type or NULL
Patches
- Return value type hint: http://felipe.ath.cx/diff/return_type_hint.diff (under construction)
- Parameter type hint: http://felipe.ath.cx/diff/param_type_hint.diff (under construction)
rfc/typehint.1207655263.txt.gz · Last modified: 2017/09/22 13:28 (external edit)