在以前的文章PHP方法参数的那点事儿中,咱们讲过关于PHP方法参数的一些小技巧。今天,咱们带来的是更加深刻的研究一下PHP中方法的参数类型。php
在PHP5以后,PHP正式引入了方法参数类型约束。也就是若是指定了方法参数的类型,那么传不一样类型的参数将会致使错误。在PHP手册中,方法的类型约束仅限于类、接口、数组或者callable回调函数。若是指定了默认值为NULL,那么咱们也能够传递NULL做为参数。git
class A{} function testA(A $a){ var_dump($a); } testA(new A()); // testA(1); // Fatal error: Uncaught TypeError: Argument 1 passed to testA() must be an instance of A, int given,
在这个例子中,咱们定义了参数类型为A类,因此当咱们传递一个标量类型时,直接就会返回错误信息。github
function testB(int $a){ var_dump($a); } testB(1); testB('52aadfdf'); // 字符串强转为int了 // testB('a'); // Fatal error: Uncaught TypeError: Argument 1 passed to testB() must be of the type int, string given function testC(string $a){ var_dump($a); } testC('测试'); testC(1); // 数字会强转为字符串 // testC(new A()); // Fatal error: Uncaught TypeError: Argument 1 passed to testC() must be of the type string
在手册中明确说明了标量类型是不能使用类型约束的。但实际上是可使用的,不过若是都是标量类型则会进行相互的强制转换,并不能起到很好的约束做用。好比上例中int和string类型进行了相互强制转换。指定了非标量类型,则会报错。此处是本文的重点,小伙伴们可要划个线了哦。其实说白了,若是咱们想指定参数的类型为固定的标量类型的话,在参数中指定并非一个好的选择,最好仍是在方法中进行再次的类型判断。并且若是参数中进行了强转,也会致使方法内部的判断产生误差。数组
最后咱们再看一看接口和匿名方法的类型约束。匿名参数类型在Laravel等框架中很是常见。微信
// 接口类型 interface D{} class childD implements D{} function testD(D $d){ var_dump($d); } testD(new childD()); // 回调匿名函数类型 function testE(Callable $e, string $data){ $e($data); } testE(function($data){ var_dump($data); }, '回调函数');
参考文档:
https://www.php.net/manual/zh/language.oop5.typehinting.php函数
===============oop
关注公众号:【硬核项目经理】获取最新文章学习
添加微信/QQ好友:【xiaoyuezigonggong/149844827】免费得PHP、项目管理学习资料测试
知乎、公众号、抖音、头条搜索【硬核项目经理】
B站ID:482780532