时时商务社区

标题: PHP中的类型约束介绍 [打印本页]

作者: bewin83    时间: 2018-2-14 05:46

            PHP的类方法和函数中可实现类型约束,但参数只能指定类、数组、接口、callable 四种类型,参数可默认为NULL,PHP并不能约束标量类型或其它类型。
如下示例:
[U]复制代码[/U] 代码如下:
test_array(array(1));
$test->test_class(new Test1());
$test->test_callable('print_r', 1);
$test->test_interface(new ArrayObject(array()));
$test->test_class_with_null();
那么对于标量类型如何约束呢?
PECL扩展库中提供了SPL Types扩展实现interger、float、bool、enum、string类型约束。
[U]复制代码[/U] 代码如下:
$int  = new  SplInt ( 94 );

try {
     $int  =  'Try to cast a string value for fun' ;
} catch ( UnexpectedValueException $uve ) {
    echo  $uve -> getMessage () .  PHP_EOL ;
}

echo  $int  .  PHP_EOL ;
/*
运行结果:
Value not an integer
94
*/
SPL Types会降低一定的灵活性和性能,实际项目中三思而行。
            
            
您可能感兴趣的文章:
  • PHP 类型转换函数intval
  • PHP 变量类型的强制转换
  • php foreach 参数强制类型转换的问题
  • php学习之数据类型之间的转换代码
  • 浅谈PHP强制类型转换,慎用!
  • 解析PHP将对象转换成数组的方法(兼容多维数组类型)
  • 浅析php数据类型转换
  • PHP中数据类型转换的三种方式
  • PHP学习笔记(三):数据类型转换与常量介绍
  • PHP类型约束用法示例
            




    欢迎光临 时时商务社区 (http://bbs.4435.cn/) Powered by Discuz! X3.2