2011-09-01 50 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; 
    ... 
} 

尋找一個構造函數,你要找的靜態初始化。