Rand()函数将静态值替换为随机值时出错


Rand() function cause error when I replace static value with random value

我做错了什么

我有这个脚本,并添加了$randnumber = rand(100, 500);函数,这应该会为我生成一个介于100和500之间的随机数。

   $randnumber = rand(100, 500);
    function word_limiter( $text, $limit = $randnumber, $chars = '0123456789' )

问题是它给了我一个错误:

分析错误:语法错误,意外T_VARIABLE

而如果我使用函数作为:

function word_limiter( $text, $limit = '200', $chars = '0123456789' )

它100%有效,我试过这样做:

function word_limiter( $text, $limit = ''.$randnumber.'', $chars = '0123456789' )

但仍然会出错?

这是一个语法错误。不能将表达式的值指定为默认值。默认值只能是常量。与其这样做,你可以做一些类似的事情:

function word_limiter ($text, $limit = null, $chars = '0123456789') {
    if ($limit === null) {
        $limit = rand(100, 500);
    }
    // ...
}

错误的做法是尝试将变量用作默认参数值。你不能这样做。

你可以这样做:

function word_limiter( $text, $limit = null, $chars = '0123456789' ){
    if (is_null($limit)){
        $limit = rand(100, 500);
    }
}

不能将变量用作参数的默认值,它必须是常数值。

你可以试试这个。。。

function word_limiter($text, $limit = NULL) {
   if ($limit === NULL) {
      // Make its default value.
   }
}