【问题标题】:How to force arguments to be integer/string如何强制参数为整数/字符串
【发布时间】:2011-07-22 18:07:30
【问题描述】:

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

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

但是对于这个函数

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

我明白了:

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

但是:

function(array $expectsArray)

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

重大更新

现在 PHP 7 supports Scalar Type Hinting

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

【问题讨论】:

标签: php arguments type-hinting


【解决方案1】:

Scalar TypeHints are available as of PHP 7:

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

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

尽管如此,在 PHP7 之前有强制标量参数的选项。

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

要发出警告,您可以使用

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
}

另类

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

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

【讨论】:

    【解决方案2】:

    你可以使用像 (int)$height 这样的“Type Juggling”。

    例如:

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

    【讨论】:

      【解决方案3】:

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

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

      您当然可以像其他人指出的那样,在您的函数/方法中检查类型,但这与强类型完全不同。想要的效果当然会以任何一种方式呈现。

      【讨论】:

      • 那么用函数检查php抛出的警告?
      • preg_replace 等函数不是用 PHP 编写的,因此不必遵守 PHP 语言的规则。您必须查阅源代码才能看到这一点,但我的直觉告诉我确实如此。
      • 可能也可能是 PHP(运行时)在内部根据函数声明检查它的情况(因为它是用 c 编写的,它具有为参数定义的类型)和然后决定做什么。函数 php_pcre_match_impl() 明确指出主题应该是 char *。
      【解决方案4】:

      如果您不使用 PHP 7.x,或者您可以使用来自 Non-standard PHP library (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');
      

      输出:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-04
        • 2011-09-27
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多