我希望我的函数期望使用字符串/整数或抛出合适的值,例如:
但是对于此功能
public function setImage($target, $source_path, integer $width, integer $height){...
我得到:
但:
function(array $expectsArray)
如我所料,我将如何获得与整数和字符串相同的效果?
大更新
PHP 7现在supports Scalar Type Hinting
function increment(int $number) {
return $number++;
}
最佳答案
Scalar TypeHints are available as of PHP 7:
PHP7之前没有标量的类型提示。 PHP 5.3.99 did have scalar typehints,但当时还没有最终确定,如果他们留下来以及他们将如何工作。
尽管如此,在PHP7之前还是有一些用于强制执行标量参数的选项。
有几个is_*
函数可以让您做到这一点,例如
is_int
— Find whether the type of a variable is integer is_string
— Find whether the type of a variable is string 要发出警告,您可以使用
trigger_error
— Generates a user-level error/warning/notice message 使用
E_USER_WARNING
的$errorType
。例子
function setInteger($integer)
{
if (FALSE === is_int($integer)) {
trigger_error('setInteger expected Argument 1 to be Integer', E_USER_WARNING);
}
// do something with $integer
}
选择
如果要拼命使用标量类型提示,请查看
该图显示了一种通过自定义错误处理程序强制执行标量类型提示的技术。
关于php - 如何强制参数为整数/字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5430126/