进入 PHPChina 首页
当前位置:PHPChina 开源社区门户 - 原创 - 正文
[字号:  ]

类与对象(PHP5)之十五:典型提示(线索)Type Hinting

发布时间:2006-9-26 14:46   作者: forest (木林森)   信息来源: 本站原创  [我来说两句(1335条)]
PHP5引入了类型提示。函数现在能给对象强制参数(在函数原型中通过指定类的名字)或数组(从PHP 5.1开始) 。
例子 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”翻译为“类型提示”不知道合适不合适?
请大家提出建议,谢谢!!

TAG: PHP5 对象

字号:   | 推荐给好友

[我来说两句(1335条)]
现在有0人对本文发表评论 查看全部评论>>评论区

 

评分:0

验证码: seccode