我收到"语法错误,意外的T_VARIABLE"错误.我不明白我做错了什么?

tru*_*ktr 3 php syntax-error parse-error

我收到此错误:"PHP Parse错误:语法错误,第66行/ var/www/vhosts/...中的意外T_VARIABLE"

这是我的代码:

function combine($charArr, $k) {

    $currentsize = sizeof($charArr);
    static $combs = array();
    static $originalsize = $currentsize; ###### <-- LINE 66 ######
    static $firstcall = true;

    if ($originalsize >= $k) {

        # Get the First Combination 
        $comb = '';
        if ($firstcall) { //if this is first call
            for ($i = $originalsize-$k; $i < $originalsize; $i++) {
                $comb .= $charArr[$i];
            }
            $combs[] = $comb; //append the first combo to the output array
            $firstcall = false; //we only want to do this during the first iteration
        }
    ....
    ....
}
Run Code Online (Sandbox Code Playgroud)

知道什么是错的吗?

Pas*_*TIN 7

引用手册 (该页面是关于静态属性,但同样适用于变量):

与任何其他PHP静态变量一样,静态属性只能使用文字或常量初始化; 表达式是不允许的.因此,虽然您可以将静态属性初始化为整数或数组(例如),但您可能不会将其初始化为另一个变量,函数返回值或对象.

你正在使用这个:

static $originalsize = $currentsize;
Run Code Online (Sandbox Code Playgroud)

哪个用表达式初始化 - 而不是常量.


这里的手册部分对静态变量的说法大致相同:

可以声明静态变量,如上面的示例所示.尝试为这些变量赋值,这些变量是表达式的结果,将导致解析错误.

而且,以防万一,这里是表达式.


在你的情况下,为了避免这个问题,我想你可以修改你的代码,所以它看起来像这样:

$currentsize = sizeof($charArr);
static $originalsize = null;
if ($originalsize === null) {
    $originalsize = $currentsize;
}
Run Code Online (Sandbox Code Playgroud)

接着就,随即 :

  • 静态变量用常量初始化
  • 如果其值为常量值,则分配动态值.