gpt4 book ai didi

php - 如何强制参数为整数/字符串

转载 作者:IT王子 更新时间:2023-10-28 23:52:44 24 4
gpt4 key购买 nike

我希望我的函数期望字符串/整数或抛出一个合适的值,例如:

warning: preg_match() expects parameter 2 to be string

但是对于这个函数

public function setImage($target, $source_path, integer $width, integer $height){...

我明白了:

Argument 4 passed to My_Helper_Image::setImage() must be an instance of integer, integer given

但是:

function(array $expectsArray)

按我的预期工作,如何实现与整数和字符串相同的效果?

重大更新

现在 PHP 7 supports Scalar Type Hinting

function increment(int $number) {
return $number++;
}

最佳答案

Scalar TypeHints are available as of PHP 7 :

Scalar type declarations come in two flavours: coercive (default) and strict. The following types for parameters can now be enforced (either coercively or strictly): strings (string), integers (int), floating-point numbers (float), and booleans (bool). They augment the other types introduced in PHP 5: class names, interfaces, array and callable.

PHP7 之前的标量没有类型提示。 PHP 5.3.99 did have scalar typehints但当时还没有最终确定他们是否会留下以及他们将如何工作。

不过,在 PHP7 之前有一些选项可以强制执行标量参数。

有几个 is_* 函数可以让你做到这一点,例如

要发出警告,您可以使用

$errorTypeE_USER_WARNING

例子

function setInteger($integer)
{
if (FALSE === is_int($integer)) {
trigger_error('setInteger expected Argument 1 to be Integer', E_USER_WARNING);
}
// do something with $integer
}

备选

如果你想拼命使用Scalar Type Hints,看看

它展示了一种通过自定义错误处理程序强制执行标量类型提示的技术。

关于php - 如何强制参数为整数/字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5430126/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com