例子 19-40. Type Hinting examples
<?php
class MyClass // An example class
{/**A test function
* First parameter must be an object of type OtherClass */
public function test(OtherClass $otherclass) { echo $otherclass->var; }
/*Another test function * First parameter must be an array*/
public function test_array(array $input_array){ print_r($input_array); }
}
class OtherClass{ public $var='Hello World'; }//Another example class
?>
Failing to satisfy the type hint results in a fatal error.
<?php
// An instance of each class
$myclass = new MyClass;
$otherclass = new OtherClass;
// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');
// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);
$myclass->test(null); //Fatal Error: Argument 1 must not be null
$myclass->test($otherclass); //Works: Prints Hello World
$myclass->test_array('a string');//Fatal Error:Argument 1 must be an array
$myclass->test_array(array('a', 'b', 'c'));//Works: Prints the array
?>
Type hinting also works with functions:
类型提示也可以与函数协同工作。
<?php
class MyClass { public $var = 'Hello World'; }//An example class
/**A test function * First parameter must be an object of type MyClass */
function MyFunction(MyClass $foo){ echo $foo->var; }
$myclass = new MyClass; //Works
MyFunction($myclass);
?>
类型提示可以只是对象和数组(从PHP 5.1开始)类型。传统的类型提示不支持整型和字符串型。
在此我把“Type Hinting”翻译为“类型提示”不知道合适不合适?
请大家提出建议,谢谢!!






