【问题标题】:How to turn public constructor into protected in child class?如何在子类中将公共构造函数变成受保护的?
【发布时间】:2011-03-27 07:26:20
【问题描述】:

我正在尝试扩展 PDO 类并将其变成单例。唯一的问题是 PDO 的构造函数是公共的,PHP 不会让我将其重写为受保护的方法。有没有什么想象的方法呢?如果我尝试这个,我会永远被那个松散的结局困住吗?另一种选择可能是不扩展 PDO,而是将其保存在静态属性中,并对其进行操作,但我希望我的类尽可能保留 PDO 的所有功能。

【问题讨论】:

  • 看看我对this question 的回答,这与您面临的问题几乎相同。

标签: php singleton pdo visibility


【解决方案1】:

您可以将 PDO 类包装在您自己的“单例工厂”对象中。基本上,您实现自己的包含(单个)PDO 实例的单例。 (注意,我不懂 PHP 语法,所以这是 Java,但你应该能明白)

MySingletonFactory.getInstance().getPDO();

更详细的解释可以在这里找到:http://www.wikijava.org/wiki/Singleton_Factory_patterns_example

(再一次,Java ......对不起 - 但我相信它会带你去你想去的地方)

【讨论】:

  • 这很好,让我思考,但唯一的问题是我还想以其他方式修改 PDO 类(添加方法)。我想我可以扩展 PDO 以添加方法,然后为该扩展类创建一个单例因子类。
【解决方案2】:

试试这个:

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();

操作。我完全搞砸了。这就是我早上回答问题的第一件事。

【讨论】:

  • 嗯。也是一个有趣的想法。使用魔术方法 __call 调用包含的 pdo 对象上的其他方法。现在我有一些决定要做。
  • 如果您使用的是5.3,您还可以使用静态调用魔术方法,这样您就不必一直调用getInstance。本质上,您将拥有在非静态上下文中工作的静态方法。
  • 在写完最后一条评论后,我意识到它并没有很好地解释我的意思,我扩展了我的示例类,添加了评论并添加了用例示例。
猜你喜欢
  • 2013-08-29
  • 2019-08-24
  • 2011-05-30
  • 2011-05-30
  • 2013-01-27
  • 2014-12-23
  • 2012-06-04
  • 2020-10-02
  • 2016-06-19
相关资源
最近更新 更多