开发者

PHP OOP Static Property Syntax Error [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 9 years ago.

Why doesn't

public static $CURRENT_TIME = time() + 7200;

work (Error):

Parse error: synta开发者_StackOverflowx 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.


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?


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜