php - PHP静态类变量可以用函数定义吗?

标签 php class static static-members

用这样的变量创建一个类工作正常:

class Example {
    public static $example = array('simple', 'example');
    // ... 
}

但是,如果我使用一个函数,在定义变量时,我会得到一个意外的'(', expecting ')'错误:

class Example {
    public static $example = explode(' ', 'simple example');
    // ... 
}

我在没有 static 关键字的情况下尝试了它,但仍然遇到相同的错误。在这样定义类变量时是否可以使用函数?有什么选择?

最佳答案

根据 the documentation (强调我的):

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.

关于php - PHP静态类变量可以用函数定义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10249977/

相关文章:

Java 为什么我的程序需要静态变量,它会导致问题吗?

php - 保护我网站的管理部分

class - Grails:将类文字存储在数据库中

class - 类实例声明的解释

Python在继承时使用带有super的类属性

c# - 如何模拟静态覆盖?

php - 多对多关系、IN 运算符和不正确结果的可能性

php preg_match 非贪婪?

php 在 screen 上使用 exec

java - 接口(interface)概念的澄清