开发者

How to turn public constructor into protected in child class?

开发者 https://www.devze.com 2023-02-19 20:23 出处:网络
I am trying to extend the PDO cla开发者_运维知识库ss as well as turn it into a singleton. The only problem is that PDO\'s constructor is public, and PHP will not let me override it as a protected meth

I am trying to extend the PDO cla开发者_运维知识库ss as well as turn it into a singleton. The only problem is that PDO's constructor is public, and PHP will not let me override it as a protected method. Is there any imaginative way around this? Will I be stuck with that loose end forever if I attempt this? An alternative may be not to extend PDO, but rather hold it in a static property, and do operations with it, but I wanted my class to retain all of the functionality of PDO if possible.


You can just wrap the PDO class in your own "Singleton Factory" object. Basically, you implement your own singleton that contains a (single) PDO instance. (Note that I don't know PHP syntax so this is Java, but you should be able to get the idea)

MySingletonFactory.getInstance().getPDO();

A more verbose explaination can be found here: http://www.wikijava.org/wiki/Singleton_Factory_patterns_example

(Again, Java ... sorry - but I believe it'll get you where you where you want to go)


Try this:

class MyPdoSingleton {

    protected $pdo;

    // Your own constructor called the first time if the singleton
    // instance does not exist
    protected function __construct() {
    }

    // Always returns the same instance (singleton)
    public static function getInstance() {
        static $instance;
        return (is_object($instance)) ? $instance : $instance = new self();
    }

    // Redirect any non static methods calls made to this class to the contained
    // PDO object.
    public function __call($method, $args) {
        return call_user_func_array(array($this->pdo, $method), $args);
    }

    // 5.3+
    public function __callStatic($method, $args) {
        $inst = self::getInstance();
        return call_user_func_array(array($inst, $method), $args);
    }

    // Or if you intend to have other classes inherit from this one
    /*public function __callStatic($method, $args) {
        $class = get_called_class();
        $inst = call_user_func(array($class, 'getInstance'));
        return call_user_func_array(array($inst, $method), $args);
    }*/

    public function myOtherMethod($arg) {
         // __call would not get called when requesting this method
    }
}

// Pre 5.3 use
$db = MyPdoSingleton::getInstance();
$db->myOtherMethod();

// Post 5.3 use
MyPdoSingleton::myOtherMethod();

Ops. I totally messed that up. That's what I get for answering questions first thing in a morning.

0

精彩评论

暂无评论...
验证码 换一张
取 消