不能在静态字段声明中使用静态函数

cannot use a static function in a static field declaration

我在 class 中有一个带有正则表达式的静态字段。此正则表达式需要一个静态数组中的值列表,因此我创建了一个静态函数,将 returns 组(例如 (a|b|c|d))插入到正则表达式中。问题是我在声明静态字段时无法调用静态函数。

我需要将函数返回的值放入字段中。

示例:

class A {
    public static function Foo()
    {
        return "Foo";
    }

    public static $Bar = "lol". self::Foo();
}

echo A::$Bar;

我明白了

Parse error: syntax error, unexpected '(', expecting ',' or ';' on line 7

我该如何解决?

您不能用 "dynamic" 值初始化静态 属性。您只能用文字或常量对其进行初始化。

您也可以在 manual 中看到这个:

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

如果你想使用静态函数就这样使用:

echo A::Foo();

与其尝试以语言不允许的方式做某事,不如倒转思路,以语言允许的方式去做:

class A {
    public static function Foo()
    {
        return "lol" . self::$Bar;
    }

    public static $Bar = "Foo";
}

echo A::Foo();