PHP OOP Static Property Syntax Error [closed]

2019-03-07 00:03发布

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.

4条回答
一夜七次
2楼-- · 2019-03-07 00:41

They have explain why it doesn't work. This would be the work around.

class SomeClass {
   public static $currentTime = null;

   __construct() {
      if (self::$currentTime === null) self::$currentTime = time() + 7200;
   }
}
查看更多
时光不老,我们不散
3楼-- · 2019-03-07 00:54

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:

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.

查看更多
forever°为你锁心
4楼-- · 2019-03-07 00:56

Others have already explained why you can't. But maybe you're looking for a work-around (Demo):

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

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

You're not looking for a constructor, you're looking for static initialization.

查看更多
走好不送
5楼-- · 2019-03-07 00:59

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:

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.

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?

查看更多
登录 后发表回答