使用作为参数给定的变量对象


Use a variable-object that was given as an argument

我有一些类有时应该在同一请求期间连接到数据库。我考虑的解决方案是将PDO对象作为方法的参数。有一个类DB()创建连接并存储到公共属性中:

class DB{
    public $conn;
    public function DB(){
        $this->conn = new PDO(...);//missed :S thxs!
    }
}
class Foo{
    public function Foo($db[, $more_possible_variables]){
        //implementing some stuff with $db
    }
}
/*index.php*/
require_once 'DB.php';
require_once 'Foo.php';
$db = new DB();
$foo = new Foo($db->conn);
/*End of index*/

我尝试了一些想法来实现这一点,但我总是遇到错误,这是不可能像处理对象一样处理变量的。我还有其他解决方案,但从效率的角度来看,不建议使用。。。

首先,请确保没有丢失对象引用$this,否则您将把PDO对象分配给局部变量,而不是成员变量。

作为一种良好的设计实践,您应该考虑使用像Singleton这样的设计模式,这将保证在这种情况下,每个请求只创建一个PDO对象实例。

您可以在PHP文档中看到这方面的示例实现。

这将是你试图实现的目标的简化版本:

class DB {
    private static $_Instance = null;
    protected $_PDOInstance = null;
    private function __construct() {
        // Create the PDO Object
        $this->_PDOInstance = new PDO(...);
    }
    public static function getInstance() {
        if(self::$_Instance !== null) {
            return self::$_Instance;
        }
        $className = __CLASS__;
        self::$_Instance = new $className;
        return self::$_Instance;
    }
}

要了解更多关于设计模式以及如何使用它们的信息,你可能想去维基百科上看一篇关于这件事的文章,或者读一本像GoF-design patterns:Elements of Reusable Object Oriented Software这样的书。