這就是所謂的Type聲明,它在PHP5中也被稱爲Type Hinting。
類型聲明允許函數將參數指定爲某些類型。如果給定值的類型不正確,則會生成一個錯誤:在PHP 5中,這將是一個可恢復的致命錯誤,而PHP 7將拋出TypeError異常。
要指定類型聲明,應該在參數名稱前添加類型名稱。如果參數的默認值設置爲NULL,則可以使聲明接受NULL值。
有效類型
Type Description Minimum PHP version
----------------------------------------------------------------------------------------------------------
Class/interface name The parameter must be an instanceof the given class PHP 5.0.0
or interface name.
----------------------------------------------------------------------------------------------------------
self The parameter must be an instanceof the same class as PHP 5.0.0
the one the method is defined on.
This can only be used on class and instance methods.
----------------------------------------------------------------------------------------------------------
array The parameter must be an array. PHP 5.1.0
----------------------------------------------------------------------------------------------------------
callable The parameter must be a valid callable. PHP 5.4.0
----------------------------------------------------------------------------------------------------------
bool The parameter must be a boolean value. PHP 7.0.0
----------------------------------------------------------------------------------------------------------
float The parameter must be a floating point number. PHP 7.0.0
----------------------------------------------------------------------------------------------------------
int The parameter must be an integer. PHP 7.0.0
----------------------------------------------------------------------------------------------------------
string The parameter must be a string. PHP 7.0.0
----------------------------------------------------------------------------------------------------------
原文出處:PHP Function Argument Type Declaration
你的情況有下面的例子來看看:
function test(array $array)
{
foreach($array as $k=>$v)
{
}
}
test(array("string")); //passed - no error
test("string"); //failed - catchable error
輸出:
Catchable fatal error: Argument 1 passed to test() must be of the type array, string given, called in /var/www/html/test/test1.php on line 12 and defined in /var/www/html/test/test1.php on line 3
我相信這意味着你需要在那裏使用一個數組。如果你不這樣做,它應該給出一個致命的錯誤 – Rasclatt