参数类型提示
PHP7 新增了形参类型提示
. int
. float
. string
. bool
代码示例:
<?php
function test(int $a,string $b,bool $c)
{
var_dump($a,$b,$c);
}
test(1,'hello world',true);
结果:
int(1) string(11) "hello world" bool(true)
如果传递与形参类型提示不一致的参数则会报错,例如
test('hello',1,'world');
Fatal error: Uncaught TypeError: Argument 1 passed to test() must be of the type integer, string given,
函数返回值类型提示
语法
<?php
function test(int $a,string $b,bool $c):string
{
return $a;
}
$res = test(1,'hello world',true);
var_dump($res); //输出 string(1) "1"
这个代码示例中,我们返回了参数$a,传递过去的是整型值,返回的也是$a,但是函数声明返回的是字符串类型,结果输出有进行类型转换,根据类型提示转为了string 类型。
如果不加函数类型返回提示,如下
<?php
function test(int $a,string $b,bool $c)
{
return $a;
}
$res = test(1,'hello world',true);
var_dump($res); //输出 int(1)
由上可以看出,函数对返回结果根据了函数类型返回提示进行约束转化,但是约束力不强,函数可以照常执行。
我们再看一个示例,函数约束返回值必须为数组
<?php
function test(int $a,string $b,bool $c):array
{
return $a;
}
$res = test(1,'hello world',true);
var_dump($res); //输出 Fatal error: Uncaught TypeError: Return value of test() must be of the type array, integer returned
可见对于函数的参数类型提示,必须严格根据参数定义的类型,但是对于函数返回值如果不一致并不影响程序执行,数组跟对象例外,如果返回值不一样会中断执行
。
如果我要对函数返回值string,int等也进行强约束呢?
严格类型约束
PHP提供了一个指令declare
示例:
<?php
declare(strict_types=1);
function test(int $a,string $b,bool $c):string
{
return $a;
}
$res = test(1,'hello world',true);
var_dump($res); //输出 Fatal error: Uncaught TypeError: Return value of test() must be of the type string, integer returned
好了强约束完成,可以放心写代码了,再也不用担心别人乱传参数。
但是注意:declare 只对当前文件生效,如果有其它文件包含的被包含文件中有声明,在包含文件中并不生效。
例如
# cls.php
<?php
declare(strict_types=1);//cls.php文件生效
# test.php
<?php
require_once 'cls.php';
//严格声明在本文件不生效。