PHP OOP Static Property Syntax Error [closed]

做~自己de王妃 提交于 2019-12-04 06:52:11

问题


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.


回答1:


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?




回答2:


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.




回答3:


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;
   }
}



回答4:


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.



来源:https://stackoverflow.com/questions/7277603/php-oop-static-property-syntax-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!