
日期:2006-09-26 作者:喜騰小二 來源:PHPChina
PHP5引入了類型提示。函式現在能給物件強制參數(在函式原型中透過指定類的名字)或陣列(從PHP 5.1開始) 。
例子 19-40. Type
Hinting examples
PHP程式碼如下:
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程式碼如下:
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程式碼如下:
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”翻譯為“類型提示”不知道合適不合適?
請大家提出建議,謝謝!!