-2

我有一个简单的单例类:

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

此代码适用于 PHP 5.3,但不适用于运行 PHP 5.2 的服务器

这里发生了什么?

4

3 回答 3

3

出乎意料T_PAAMAYIM_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`'));
于 2013-09-20T03:31:32.000 回答
0

The issue here is that you are creating an instance of a class to access a static variable.

The correct way to access a static variable in this context is by using the class name and the Scope Resolution Operator "T_PAAMAYIM_NEKUDOTAYIM" like this

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

and so on.

Now with that said, all you need to do is make some of the static properties like @GeorgeMarquest suggested, otherwise it is of no use to have a unique static instance (a singleton) of your class an a bunch of static variables since they can be access without the need to construct an object, see.

Take a look at the following site to understand better the Singleton Design Pattern and see and actual PHP example.

It may be worth for you to take a look at the following post Why global variables are bad and evaluate whether or not you need a singleton.

于 2013-09-20T03:48:05.023 回答
0

“从 PHP 5.3.0 开始,可以使用变量来引用类”。

PHP 5.2中,这样做:

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

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

// ERROR
$a::$static_db;

// OK
A::$static_db;
于 2013-09-20T03:38:23.080 回答