Php 为方法参数设置允许的变量类型
在一些编程语言(如Java或C)中,允许程序员设置允许的输入变量类型。我使用PHP,我也希望这样做,以避免向我的方法/函数传递错误的数据 我的代码:Php 为方法参数设置允许的变量类型,php,variables,Php,Variables,在一些编程语言(如Java或C)中,允许程序员设置允许的输入变量类型。我使用PHP,我也希望这样做,以避免向我的方法/函数传递错误的数据 我的代码: public static function generateFiles(array $data, Custom_Pager $pager) {...} 为什么这是允许的,而我不能这样写: public static function generateFiles(array $data, Custom_Pager $pager, int $lim
public static function generateFiles(array $data, Custom_Pager $pager)
{...}
为什么这是允许的,而我不能这样写:
public static function generateFiles(array $data, Custom_Pager $pager, int $limit, string $text)
{ ... }
function getVar($var,$type) {
switch($type) {
case "int":
return (int)$var;
case "string":
return (string)$var;
}
}
有没有办法标准化我在上面介绍的第一个和第二个方法声明?如果没有,原因是什么?PHP是一种语言,所以这是不可能的
引入了PHP5.1,尽管它有其局限性:
类型提示不能与int或string等标量类型一起使用。
特质也是不允许的
是的,您可以使用强制将参数设置为特定类型,但它显然不适用于基本类型 但是,如果参数值不符合预期,则可以在方法中引发异常
if (!is_int($param))
throw new Exception('param must be int.');
我做了一个强制类型暗示的函数。它的工作原理如下:
public static function generateFiles(array $data, Custom_Pager $pager, int $limit, string $text)
{ ... }
function getVar($var,$type) {
switch($type) {
case "int":
return (int)$var;
case "string":
return (string)$var;
}
}
您可以继续使用所有其他类型。您还可以使用相同的方法来检查变量的is_int、is_string、is_bool等。这不是不可能的,只是比您想象的要难——您的函数将类似于generateFile(getArray($var1)、getBool($var2)、getInt($var3));例如,对于getArray,您可以执行以下操作:if(is_array($var)){return$var;}else{return array($var);}