From 725924e665c85dc385346f0727babe988c73ae58 Mon Sep 17 00:00:00 2001 From: Jakub Vrana Date: Tue, 13 Mar 2012 01:39:06 +0000 Subject: [PATCH] Interface, children, callable, trait git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@324171 c90b9560-bf6c-de11-be94-00142212c4b1 --- language/oop5/typehinting.xml | 45 ++++++++++++++++++++++++++++------- 1 file changed, 36 insertions(+), 9 deletions(-) diff --git a/language/oop5/typehinting.xml b/language/oop5/typehinting.xml index 0bd352ceea..713db1da92 100644 --- a/language/oop5/typehinting.xml +++ b/language/oop5/typehinting.xml @@ -3,13 +3,25 @@ Type Hinting - PHP 5 introduces Type Hinting. Functions are now able to force parameters + PHP 5 introduces type hinting. Functions are now able to force parameters to be objects (by specifying the name of the class in the function - prototype) or arrays (since PHP 5.1). However, if NULL is used + prototype), interfaces, arrays (since PHP 5.1) or callable + (since PHP 5.4). However, if NULL is used as the default parameter value, it will be allowed as an argument for any later call. + + If class or interface is specified as type hint then all its children or + implementations are allowed too. + + + + Type hints can not be used with scalar types such as int or + string. + Traits are not allowed either. + + Type Hinting examples @@ -36,6 +48,20 @@ class MyClass public function test_array(array $input_array) { print_r($input_array); } + + /** + * First parameter must be iterator + */ + public function test_interface(Traversable $iterator) { + echo get_class($iterator); + } + + /** + * First parameter must be callable + */ + public function test_callable(callable $callback, $data) { + call_user_func($callback, $data); + } } // Another example class @@ -73,6 +99,12 @@ $myclass->test_array('a string'); // Works: Prints the array $myclass->test_array(array('a', 'b', 'c')); + +// Works: Prints ArrayObject +$myclass->test_interface(new ArrayObject(array())); + +// Works: Prints int(1) +$myclass->test_callable('var_dump', 1); ?> ]]> @@ -92,13 +124,13 @@ class MyClass { * * First parameter must be an object of type MyClass */ -function MyFunction (MyClass $foo) { +function myFunction(MyClass $foo) { echo $foo->var; } // Works $myclass = new MyClass; -MyFunction($myclass); +myFunction($myclass); ?> ]]> @@ -121,11 +153,6 @@ test(new stdClass); ]]> - - Type Hints can only be of the object and array - (since PHP 5.1) type. Traditional type hinting with int and - string isn't supported. -