在之前的文章PHP方法引數的那點事兒中,我們講過關于PHP方法引數的一些小技巧,今天,我們帶來的是更加深入的研究一下PHP中方法的引數型別,
在PHP5之后,PHP正式引入了方法引數型別約束,也就是如果指定了方法引數的型別,那么傳不同型別的引數將會導致錯誤,在PHP手冊中,方法的型別約束僅限于類、介面、陣列或者callable回呼函式,如果指定了默認值為NULL,那么我們也可以傳遞NULL作為引數,
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類,所以當我們傳遞一個標量型別時,直接就會回傳錯誤資訊,
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://github.com/zhangyue0503/dev-blog/blob/master/php/202001/%E5%85%B3%E4%BA%8EPHP%E7%9A%84%E6%96%B9%E6%B3%95%E5%8F%82%E6%95%B0%E7%B1%BB%E5%9E%8B%E7%BA%A6%E6%9D%9F.md
參考檔案:
https://www.php.net/manual/zh/language.oop5.typehinting.php
===============
關注公眾號:【硬核專案經理】獲取最新文章
添加微信/QQ好友:【xiaoyuezigonggong/149844827】免費得PHP、專案管理學習資料
知乎、公眾號、抖音、頭條搜索【硬核專案經理】
B站ID:482780532
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/263202.html
標籤:PHP
上一篇:Java 模擬資料庫連接池的實作
下一篇:PHP記憶體溢位是什么樣的
