PHP中的类型约束介绍
PHP的类方法和函数中可实现,但参数只能指定类、数组、接口、callable 四种类型,参数可默认为NULL,PHP并不能约束标量类型或其它类型。 如下示例: 代码如下: class Test
{ public function test_array(array $arr) { print_r($arr); } public function test_class(Test1 $test1 = null) public function test_callable(callable $callback,$data) public function test_interface(Traversable $iterator) public function test_class_with_null(Test1 $test1 = NULL) } class Test1{} $test = new Test(); //函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。 $test->test_array(array(1)); 那么对于标量类型如何约束呢? PECL扩展库中提供了SPL Types扩展实现interger、float、bool、enum、string类型约束。 代码如下: try {
$int = 'Try to cast a string value for fun' ; } catch ( UnexpectedValueException $uve ) { echo $uve -> getMessage () . PHP_EOL ; } echo $int . PHP_EOL ; 会降低一定的灵活性和性能,实际项目中三思而行。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |