PHP中的类型约束介绍
网络编程 2021-07-05 09:09www.168986.cn编程入门
这篇文章主要介绍了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
*/
会降低一定的灵活性和性能,实际项目中三思而行。
编程语言
- 机械手焊接机器人编程 机械手焊接设备编程
- vb数据库编程实例,vb做数据库
- tiobe世界编程语言排行榜,全球编程语言排行
- 成都java编程培训 成都it编程培训中心
- 编程基础培训,编程基础知识培训
- flash游戏编程基础教程,flash游戏开发教程
- 不会英语能学编程吗 不会英语可以学程序员吗
- 爱心代码编程C语言 爱心代码编程c语言公式
- c语言编程学习入门 c语言编程快速入门
- 西门子plc编程培训 西门子plc编程培训班
- 哪里可以学编程 台州哪里可以学编程
- 少儿编程哪个好 少儿编程哪个品牌好
- 编程是什么意思,图形编程是什么意思
- c语言编程软件下载,c语言编程软件在哪下载
- java编程软件下载,java编程下载手机版
- ug编程培训学校,ug编程培训教程