Php Can';t访问singleton的静态类成员

Php Can';t访问singleton的静态类成员,php,singleton,php-5.2,Php,Singleton,Php 5.2,我有一个简单的singleton类: class controller { // Store the single instance of controller private static $_controller = null; public static $user; public static $db; public static $page; public static $code; // construct the clas

我有一个简单的singleton类:

class controller {

    // Store the single instance of controller
    private static $_controller = null;
    public static $user;
    public static $db;
    public static $page;
    public static $code;

    // construct the class and set up the user & db instances
    private function __construct() {
        self::$db = new db(HOST, USER, PASS, DB);
        self::$user = new user();
        self::$page = new page();
        self::$code = new code();
    }

    // Getter method for creating/returning the single instance of this class
    public static function getInstance() {
        if (!self::$_controller) {                        
            self::$_controller = new self();
        }

        return self::$_controller;
    }
}
我这样称呼(并测试)它:

$load = controller::getInstance();
print_r($load::$db->query('SELECT * FROM `users`'));
但是我从PHP中得到了这个错误:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM
此代码适用于PHP5.3,但不适用于运行PHP5.2的服务器


这是怎么回事?

意想不到的
T\u PAAMAYIM\u NEKUDOTAYIM
是这行中的双冒号(
):

print_r($load::$db->query('SELECT * FROM `users`'));
一个单例类应该能够创建一个且只能创建一个实例,该实例必须随时可用。实例应该保存数据,但您使用的是静态属性。您应该删除静态属性(或者完全避免创建实例)

因此,如果要保持此静态,请使用类名直接访问:

print_r(controller::$db->query('SELECT * FROM `users`'));
或者,如果您移除了静电传感器:

class controller {

    // Store the single instance of controller
    private static $_controller = null;
    public $user;
    public $db;
    public $page;
    public $code;

    // construct the class and set up the user & db instances
    private function __construct() {
        $this->db = new db(HOST, USER, PASS, DB);
        $this->user = new user();
        $this->page = new page();
        $this->code = new code();
    }

    ...// the rest as it is
打电话时要这样做:

$load = controller::getInstance();
print_r($load->db->query('SELECT * FROM `users`'));
“从PHP5.3.0开始,可以使用变量引用类”

PHP5.2
中,按以下方式执行:

class A {
    public $db;
    public static $static_db;
}

// OK
$a = new A();
$a->db;

// ERROR
$a::$static_db;

// OK
A::$static_db;

这里的问题是您正在创建一个类的实例来访问一个静态变量

在此上下文中访问静态变量的正确方法是使用类名和范围解析运算符
“T_PAAMAYIM_NEKUDOTAYIM”
,如下所示

Controller::$user; 
Controller::$db; 
等等

话虽如此,您所需要做的只是使一些静态属性如@GeorgeMarquest建议的那样,否则将类的唯一静态实例(单例)作为一组静态变量是没有用的,因为它们可以访问,而无需构造对象

看一下下面的网站,更好地了解和了解实际情况


也许你值得看看下面的帖子,评估一下你是否需要单身

请停止在代码中使用单例。此外,您可能会考虑PHP 5.3已经不支持几个月(以及5.2年- 2年前)的事实。您确实应该更新服务器或移动到其他主机。您的实例不应该具有静态属性,如
$db
$user
$page
$code
。实例应该具有对象属性。这是您的确切代码的复制粘贴吗?此错误通常意味着您的
位置应该是
如果更新服务器不是此开发人员的选项,该怎么办?当然,这是最好的解决方案,但并不总是可行的选择。@tereško-我们没有对当前服务器的物理访问权限,因为它由另一家公司托管。他们对这类事情都很挑剔。我们正在使用自己的服务器迁移到另一台主机。此解决方案有效。谢谢感谢Onema提供的额外信息,这个项目只有少数人可以在内部访问。我将读到:)