views:

32

answers:

1

I have a function that gets a value from the database and returns it. I call the function to store it into a member variable but I get the following error:

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

This is the line that causes the error

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

And this is the function that gets the value from the database

    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().

all of this code is in the same class. Anyone an idea of what's causing the error?

+3  A: 

Class properties may not be declared with run-time information.

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

The above will not work.

See the PHP Manual on Class Properties: (emphasis mine)

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.

You could create a getter for $depositmoney and have it initialize the value if it is currently unset:

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

However, I suggest to get rid of the static and use instance methods and properties instead to track the state. You will also want to get rid of the global stuff and inject dependencies through the constructor, setters or during the method invocation. That decreases coupling and will make the code more maintainable.

Gordon