您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

PHP中的类型约束

2024/4/29 20:35:41发布19次查看
本文主要介绍了php中的类型约束介绍,php的类方法和函数中可实现类型约束,但参数只能指定类、数组、接口、callable 四种类型,参数可默认为null,php并不能约束标量类型或其它类型。希望本文对大家有所帮助。
php的类方法和函数中可实现类型约束,但参数只能指定类、数组、接口、callable 四种类型,参数可默认为null,php并不能约束标量类型或其它类型。
如下示例:
<?php class test { public function test_array(array $arr) { print_r($arr); } public function test_class(test1 $test1 = null) { print_r($test1); } public function test_callable(callable $callback, $data) { call_user_func($callback, $data); } public function test_interface(traversable $iterator) { print_r(get_class($iterator)); } public function test_class_with_null(test1 $test1 = null) { } } class test1{} $test = new test(); //函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。 $test->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类型约束。
$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 数据类型和判断变量类型
php 函数注意
一些被忽视的 php 函数(整理)
以上就是php中的类型约束的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product