PHP - 为什么不能使用~PHP_INT_MAX作为默认参数

时间:2013-09-05 18:27:50

标签: php

我写了一个函数,其中我使用PHP_INT_MAX~PHP_INT_MAX作为默认参数,但我最终得到了'〜'的语法错误。声明是:

public static function isNumberValid($number, $lowerbound = ~PHP_INT_MAX, $upperbound = PHP_INT_MAX)

我通过在声明中创建$lowerbownd = null然后将其设置在正文中来修复它,现在它完全正常工作:

if (is_null($lowerbound)){
    $lowerbound = ~PHP_INT_MAX;
}

我只是想知道为什么会这样......

3 个答案:

答案 0 :(得分:5)

可选变量的默认值必须是常量,例如,类中变量或常量的初始值。 ~PHP_INT_MAX不是常数,而是表达式。 (你也不能使用2 + 2。)

There’s was an RFC relating to this.

答案 1 :(得分:4)

参数的默认值必须是常量。如果要使用~PHP_INT_MAX,可以使用该值定义另一个常量并使用此常量:

define('PHP_INT_MIN', ~PHP_INT_MAX);

public static function isNumberValid($number, $lowerbound = PHP_INT_MIN, $upperbound = PHP_INT_MAX)

答案 2 :(得分:2)

函数参数的默认值必须是常量值。他们不能成为一种表达。尽管PHP_INT_MAX是一个编译值,并且可以立即用于编译器,但仍然可以通过执行逐位NOT操作使其成为表达式。

function foo ($x = PHP_INT_MAX) { echo 'this is ok'; }
function bar ($x = ~PHP_INT_MAX) { echo 'this is NOT ok'; }
相关问题