【发布时间】:2017-09-25 10:57:38
【问题描述】:
在尝试使用 OOP 的 PHP 时,我在 Stackoverflow 上遇到了关于 PDO 的讨论,而不是使用全局变量和单例。我看到了这个问题 How to properly set up a PDO connection 展示了一种为 PDO 使用工厂模式和匿名函数的方法。我只是无法理解其中的一部分
class StructureFactory
{
protected $provider = null;
protected $connection = null;
public function __construct( callable $provider )
{
$this->provider = $provider;
}
public function create( $name)
{
if ( $this->connection === null )
{
$this->connection = call_user_func( $this->provider );
}
return new $name( $this->connection );
}
}
我不明白的部分是
return new $name( $this->connection );
$name 是回调吗?或者它是一个对象?为什么 $this->conection 作为参数传递?提前谢谢你
【问题讨论】:
-
$name应该是new实例的类名。为什么这段代码没有很好的文档记录? -
当您知道变量
$this->connection不持有mysql 连接,而是持有PDO实例时,也许会更清楚一点。 -
@JustOnUnderMillions
something = $factory->create('Something');这就是它的使用方式。你能再解释一下吗?我无法理解如何在另一个类方法中使用 pdo