PHP OOP 静态属性语法错误 [英] PHP OOP Static Property Syntax Error

查看:29
本文介绍了PHP OOP 静态属性语法错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不

public static $CURRENT_TIME = time() + 7200;

工作(错误):

解析错误:语法错误,意外的'('

Parse error: syntax error, unexpected '('

但是

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

确实有效.

我是 OOP 的新手,我很困惑.

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.

来自 PHP 手册:

这个声明可以包含一个初始化,但是这个初始化必须是一个常量值——也就是说,它必须能够在编译时被评估,并且不能依赖于运行时信息来被评估.

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?

这篇关于PHP OOP 静态属性语法错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆