Search code examples
phpsingletonphp-5.2

Can't access static class members of singleton


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?


Solution

  • 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`'));