在以前的文章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