2010-06-21 84 views
0

我有一個函數從數據庫中獲取一個值並返回它。我調用該函數將其存儲到一個成員變量,但我得到了以下錯誤:php class:從函數獲取值到成員變量的問題

Parse error: parse error, expecting `','' or `';'' in I:\wamp\www\deposit\classes\Site.php on line 14 

這是導致該錯誤

public static $depositmoney = self::get_balance(); 

線路,這是從獲得的價值功能數據庫

public static function get_balance() 
    { 
     global $link, $usertable, $userid, $useridentify; 

     //query current balance 
     $cb = mysqli_fetch_object(mysqli_query($link, "SELECT deposit FROM ".$usertable." WHERE ".$userid."=".$useridentify."")); 
     return $cb->deposit; 

    }//end of function get_balance(). 

所有這些代碼都在同一個類中。任何人都知道是什麼導致了錯誤?

回答

3

類屬性不能用運行時信息聲明。

public static $depositmoney = self::get_balance(); 

以上將不起作用。

PHP Manual on Class Properties:(重點煤礦)

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. 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.

你可以爲$depositmoney創造一個getter和有它初始化值,如果它是目前取消設置:

public static function getDepositMoney() 
{ 
    if(self::$depositmoney === NULL) { 
     self::$depositmoney = self::get_balance(); 
    } 
    return self::$depositmoney; 
} 

不過,我建議得到擺脫static,並使用實例方法和屬性來追蹤狀態。你也希望擺脫global的東西,並通過構造函數,setter或方法調用注入依賴關係。這減少了耦合,並將使代碼更易於維護。