du3979 2013-09-20 03:20
浏览 39
已采纳

无法访问单例的静态类成员[重复]

I have a simple singleton class:

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

And I call (and test) it like this:

$load = controller::getInstance();
print_r($load::$db->query('SELECT * FROM `users`'));

But then I get this error from PHP:

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

This code works with PHP 5.3, but not on a server running PHP 5.2

What's going on here?

</div>
  • 写回答

3条回答 默认 最新

  • dongqiang5932 2013-09-20 03:31
    关注

    The unexpected T_PAAMAYIM_NEKUDOTAYIMis the double colon (::) in this line:

    print_r($load::$db->query('SELECT * FROM `users`'));
    

    A singleton class should be able to create one and only one instance, which must be readily available. The instance should hold the data, but instead you used static properties. You should remove the static properties (or avoid creating an instance at all).

    So, if you want to keep this static, access directly with the class name:

    print_r(controller::$db->query('SELECT * FROM `users`'));
    

    Or, if you remove the static:

    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
    

    And do this when calling:

    $load = controller::getInstance();
    print_r($load->db->query('SELECT * FROM `users`'));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能