Why doesn't
public static $CURRENT_TIME = time() + 7200;
work (Error):
Parse error: syntax error, unexpected '('
but
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;
}
}
does work.
I'm new to OOP, I'm so confused.
They have explain why it doesn't work. This would be the work around.
Class members can only contain constants and literals, not the result of function calls, as it is not a constant value.
From the PHP Manual:
Others have already explained why you can't. But maybe you're looking for a work-around (Demo):
You're not looking for a constructor, you're looking for static initialization.
You cannot initialize any member variable (property) with a non-constant expression. In other words, no calling functions right there where you declare it.
From the PHP manual:
The best answer I can give as to why? Because the static field initializers aren't really run with any sort of context. When a static method is called, you are in the context of that function call. When a non-static property is set, you are in the context of the constructor. What context are you in when you set a static field?