2011-09-01 75 views
-1

为什么不PHP OOP静态属性语法错误

public static $CURRENT_TIME = time() + 7200; 

工作(错误):

Parse error: syntax error, unexpected '('

class Database { 
    public static $database_connection; 

    private static $host = "xxx"; 
    private static $user = "xxx"; 
    private static $pass = "xxx"; 
    private static $db = "xxx"; 

    public static function DatabaseConnect(){ 
    self::$database_connection = new mysqli(self::$host,self::$user,self::$pass,self::$db); 
    self::$database_connection->query("SET NAMES 'utf8'"); 
    return self::$database_connection; 
    } 
} 

确实工作。

我是OOP的新手,我很困惑。

+1

定义“不起作用”。 –

+0

对不起,它出错了。 –

+1

你收到什么错误? –

回答

7

您不能使用非常量表达式初始化任何成员变量(属性)。换句话说,在你声明它的地方没有调用函数。

PHP manual

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

最好的答案我可以给为为什么?因为静态字段初始值设定程序并不真正运行任何类型的上下文。当一个静态方法被调用时,你处于该函数调用的上下文中。当设置非静态属性时,您处于构造函数的上下文中。当你设置一个静态字段时,你处于什么样的环境?

+0

+1与静态和良好的“直接从马口”报价通过手册无关 – webbiedave

+0

我想从这得到的是为什么设置一个静态方法内的属性工作,但不是一个方法之外的静态属性 –

+0

@ShaneLarson请参阅我的编辑以获取关于“为什么”的答案 –

3

类成员只能包含常量和文字,而不是函数调用的结果,因为它不是一个常量值。

PHP 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.

+1

没有类成员可以包含函数调用的结果,static或not。 –

+0

您是对的 – johnluetke

+0

接收'E_STRICT'?否,您将收到解析错误。 – webbiedave

1

他们必须解释为什么它不工作。这将是工作。

class SomeClass { 
    public static $currentTime = null; 

    __construct() { 
     if (self::$currentTime === null) self::$currentTime = time() + 7200; 
    } 
} 
0

其他人已经解释了为什么你不能。但是,也许你正在寻找一个变通办法(Demo):

My_Class::$currentTime = time() + 7200; 

class My_Class 
{ 
    public static $currentTime; 
    ... 
} 

寻找一个构造函数,你要找的静态初始化。