如何使用匿名函数和闭包正确设置PDO连接

时间:2017-01-09 07:41:51

标签: php mysql pdo closures anonymous-function

在关于类似主题Answer by "teresko"的帖子的答案的帮助下,我设法理解了建立与我的数据库的连接的工厂设计方法。但我无法在我的代码中实现逻辑,因为我收到此错误:

致命错误:第42行的C:\ somewhere \ db2.php中找不到类'conn'

这是我的db文件:

$provider = function() {
    $db_user="root"; // db user
    $db_password="";// db password (mention your db password here)
    $db_database="cl";// database name
    $db_host="localhost"; // db server

    $instance = new PDO("mysql:host=$db_host;dbname=$db_database", $db_user, $db_password);
    $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    return $instance;
};

$factory = new StructureFactory( $provider );
$conn = $factory->create('conn');

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

由于我是新用户,因此我无法将此问题作为对原始答案的评论。你能帮我解决一下我出错的地方吗?正如最初的问题所说:“我真的想知道如何使用PHP和PDO正确连接到MySQL数据库并使其易于访问。我渴望学习......”

1 个答案:

答案 0 :(得分:0)

鉴于您是新用户,只需将其设为简单的PDO实例。

$db_user="root"; // db user
$db_password="";// db password (mention your db password here)
$db_database="cl";// database name
$db_host="localhost"; // db server
$db_charset="utf8";

$conn = new PDO("mysql:host=$db_host;dbname=$db_database;charset=$db_charset", $db_user, $db_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);