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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5430126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 21:23:20  来源:igfitidea点击:

How to force arguments to be integer/string

phpargumentstype-hinting

提问by Moak

I'd like my functions to expect strings/integers or throw a fit, like:

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

warning: preg_match() expects parameter 2 to be string

警告:preg_match() 期望参数 2 是字符串

However for this function

但是对于这个功能

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

I get:

我得到:

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

传递给 My_Helper_Image::setImage() 的参数 4 必须是整数的实例,整数给定

But:

但:

function(array $expectsArray)

works as I expect, how would I achieve the same effect as with integers and strings?

如我所料,如何实现与整数和字符串相同的效果?

Big Update

大更新

PHP 7 now supports Scalar Type Hinting

PHP 7 现在支持标量类型提示

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

回答by Gordon

Scalar TypeHints are available as of PHP 7:

标量类型提示从 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.

标量类型声明有两种风格:强制(默认)和严格。现在可以强制执行以下参数类型(强制或严格):字符串 (string)、整数 (int)、浮点数 (float) 和布尔值 (bool)。它们扩充了 PHP 5 中引入的其他类型:类名、接口、数组和可调用。

There is no Type Hints for scalars before PHP7. PHP 5.3.99 did have scalar typehintsbut it wasn't finalised at that point if they stay and how they will work then.

PHP7 之前没有标量的类型提示。PHP 5.3.99 确实有标量类型提示,但当时还没有最终确定它们是否保留以及它们将如何工作。

Nevertheless, there is options for enforcing scalar arguments before PHP7.

尽管如此,在 PHP7 之前有一些选项可以强制执行标量参数。

There is a couple of is_*functions that let you do that, e.g.

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

To raise a Warning, you'd use

要发出警告,您可以使用

with an E_USER_WARNINGfor $errorType.

带有E_USER_WARNINGfor $errorType

Example

例子

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

Alternative

选择

If you want to use Scalar Type Hints desperately, have a look at

如果你想拼命使用标量类型提示,看看

which shows a technique for enforcing scalar typehints via a custom Error Handler.

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

回答by Frank

You can use "Type Juggling" like (int)$height.

您可以使用“类型杂耍”,例如 (int)$height。

For example:

例如:

function setImage($target, $source_path, integer $width, $height) {
    $height = (int)$height;
    ...
}

回答by Peter Lindqvist

PHP does not (yet) implement strong typing, therefore you cannot force a parameter to be an integer. It does only apply to classes (the error you get imply that $width should be an instance of class integer) and arrays.

PHP 还没有(还)实现强类型,因此您不能强制参数为整数。它只适用于类(你得到的错误暗示 $width 应该是类整数的实例)和数组。

Type hinting for classes is available in PHP 5, type hinting for arrays starting with 5.1, and apparently scalar type hinting may (or may not) be available in the future.

类的类型提示在 PHP 5 中可用,数组的类型提示从 5.1 开始,显然标量类型提示将来可能(也可能不)可用。

You can of course as others have pointed out, check for type within your function/method, but that is fundamentally different from strong typing. The desired effect will of course be present either way.

您当然可以像其他人指出的那样,检查您的函数/方法中的类型,但这与强类型有着根本的不同。所需的效果当然会以任何方式出现。

回答by Ihor Burlachenko

If you are not using PHP 7.x or you can use argsmodule from Non-standard PHP library (NSPL). It is not as fancy and PHP 7.x type-hinting but does the validation:

如果您没有使用 PHP 7.x,或者您可以使用来自非标准 PHP 库 (NSPL) 的args模块。它不像 PHP 7.x 类型提示那样花哨,但会进行验证:

use const \nspl\args\numeric;
use function \nspl\args\expects;

function sqr($x)
{
    expects(numeric, $x);
    return $x * $x;
}

sqr('hello world');

Outputs:

输出:

InvalidArgumentException: Argument 1 passed to sqr() must be numeric, string given in /path/to/example.php on line 17

Call Stack:
    0.0002     230304   1. {main}() /path/to/example.php:0
    0.0023     556800   2. sqr() /path/to/example.php:17