当前位置:首页 > PHP教程 > php应用 > 列表

PHP中的类型约束介绍

发布:smiling 来源: PHP粉丝网  添加日期:2021-05-26 15:16:51 浏览: 评论:0 

这篇文章主要介绍了PHP中的类型约束介绍,PHP的类方法和函数中可实现类型约束,但参数只能指定类、数组、接口、callable 四种类型,参数可默认为NULL,PHP并不能约束标量类型或其它类型,需要的朋友可以参考下。

PHP的类方法和函数中可实现类型约束,但参数只能指定类、数组、接口、callable 四种类型,参数可默认为NULL,PHP并不能约束标量类型或其它类型。

如下示例:

  1. <?php 
  2.  
  3. class Test 
  4. { 
  5.     public function test_array(array $arr) 
  6.     { 
  7.         print_r($arr); 
  8.     } 
  9.  
  10.     public function test_class(Test1 $test1 = null) 
  11.     { 
  12.         print_r($test1); 
  13.     } 
  14.  
  15.     public function test_callable(callable $callback, $data) 
  16.     { 
  17.         call_user_func($callback, $data); 
  18.     } 
  19.  
  20.     public function test_interface(Traversable $iterator) 
  21.     { 
  22.         print_r(get_class($iterator)); 
  23.     } 
  24.  
  25.     public function test_class_with_null(Test1 $test1 = NULL) 
  26.     { 
  27.  
  28.     } 
  29. } 
  30.  
  31. class Test1{} 
  32.  
  33. $test = new Test(); 
  34.  
  35. //函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。 
  36.  
  37. $test->test_array(array(1)); 
  38. $test->test_class(new Test1()); 
  39. $test->test_callable('print_r', 1); 
  40. $test->test_interface(new ArrayObject(array())); 
  41. $test->test_class_with_null(); 

那么对于标量类型如何约束呢?

PECL扩展库中提供了SPL Types扩展实现interger、float、bool、enum、string类型约束,代码如下:

  1. $int  = new  SplInt ( 94 ); 
  2.  
  3. try { 
  4.      $int  =  'Try to cast a string value for fun' ; 
  5. } catch ( UnexpectedValueException $uve ) { 
  6.     echo  $uve -> getMessage () .  PHP_EOL ; 
  7. } 
  8.  
  9. echo  $int  .  PHP_EOL ; 
  10. /* 
  11. 运行结果: 
  12. Value not an integer 
  13. 94 
  14. */ 

SPL Types会降低一定的灵活性和性能,实际项目中三思而行。

Tags: PHP类型约束

分享到: