所谓类型约束就是定义一个变量的时候,必须指定其类型,并且以后该变量也只能存储该类型数据。在这篇文章中,我将给大家介绍一下php类型约束以及用法。
php类型约束的介绍
php是弱类型语言,其特点就是无需为变量指定类型,而且在其后也可以存储任何类型,当然这也是使用php能快速开发的关键点之一。但是自php5起,我们就可以在函数(方法)形参中使用类型约束了。
函数的参数可以指定的范围如下:
1、必须为对象(在函数原型里面指定类的名字);
2、接口;
3、数组(php 5.1 起);
4、callable(php 5.4 起)。
5、如果使用 null 作为参数的默认值,那么在调用函数的时候依然可以使用 null 作为实参。
6、如果一个类或接口指定了类型约束,则其所有的子类或实现也都如此。
注意:在php7以前,类型约束不能用于标量类型如 int 或 string。traits 也不允许。
php类型约束的用法:
下面是官方给的例子:
<?php//如下面的类class myclass{ /** * 测试函数 * 第一个参数必须为 otherclass 类的一个对象 */ public function test(otherclass $otherclass) { echo $otherclass->var; } /** * 另一个测试函数 * 第一个参数必须为数组 */ public function test_array(array $input_array) { print_r($input_array); }} /** * 第一个参数必须为递归类型 */ public function test_interface(traversable $iterator) { echo get_class($iterator); } /** * 第一个参数必须为回调类型 */ public function test_callable(callable $callback, $data) { call_user_func($callback, $data); }}// otherclass 类定义class otherclass { public $var = 'hello world';}?>
函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。
<?php// 两个类的对象$myclass = new myclass;$otherclass = new otherclass;// 致命错误:第一个参数必须是 otherclass 类的一个对象$myclass->test('hello');// 致命错误:第一个参数必须为 otherclass 类的一个实例$foo = new stdclass;$myclass->test($foo);// 致命错误:第一个参数不能为 null$myclass->test(null);// 正确:输出 hello world $myclass->test($otherclass);// 致命错误:第一个参数必须为数组$myclass->test_array('a string');// 正确:输出数组$myclass->test_array(array('a', 'b', 'c'));// 正确:输出 arrayobject$myclass->test_interface(new arrayobject(array()));// 正确:输出 int(1)$myclass->test_callable('var_dump', 1);?>
类型约束不只是用在类的成员函数里,也能使用在函数里:
<?php// 如下面的类class myclass { public $var = 'hello world';}/** * 测试函数 * 第一个参数必须是 myclass 类的一个对象 */function myfunction (myclass $foo) { echo $foo->var;}// 正确$myclass = new myclass;myfunction($myclass);?>
类型约束允许 null 值:
<?php/* 接受 null 值 */function test(stdclass $obj = null) {}test(null);test(new stdclass);?>
php7
标量类型声明 (php 7)
标量类型声明 有两种模式: 强制 (默认) 和 严格模式。
现在可以使用下列类型参数(无论用强制模式还是严格模式):
1、字符串(string),
2、整数 (int),
3、浮点数 (float),
4、布尔值 (bool)。
它们扩充了php5中引入的其他类型:类名,接口,数组和 回调类型。
以上范例的运行结果会输出:int(9)
要使用严格模式,一个 declare 声明指令必须放在文件的顶部。这意味着严格声明标量是基于文件可配的。 这个指令不仅影响参数的类型声明,也影响到函数的返回值声明。
相关文章推荐:
php中的类型约束介绍,php类型约束介绍
php中类型约束的思路代码分享如何使用类型约束来限定php函数类型
以上就是php类型约束是什么?php类型约束简介和用法的详细内容。