PHP:PDO连接设置错误

PHP:PDO连接设置错误,php,mysql,pdo,Php,Mysql,Pdo,在我的数据库文件中: class StructureFactory { // Default values protected $provider = null; protected $connection = null; // When Class is called, we send the $provider to it public function __construct( callable $provider ) {

在我的数据库文件中:

class StructureFactory
{
    // Default values
    protected $provider = null;
    protected $connection = null;

    // When Class is called, we send the $provider to it
    public function __construct( callable $provider )
    {
        // replace the $provider in the Class to the sent in $provider
        $this->provider = $provider;
    }

    public function create( $name )
    {
        if ( $this->connection === null )
        {
            // Create a new connection with the send in name
            $this->connection = call_user_func( $this->provider );
        }
        return new $name( $this->connection );
    }

}


$provider = function()
{
    // New provider variables
    $instance = new PDO('mysql:dbname:DBNAME;host=localhost;charset=utf8', 'userHERE', 'passHERE');
    $instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    return $instance;
};

// send the new provider
$factory = new StructureFactory( $provider );

// Create a new connection with $db
function open_database($factory){
    $db = $factory->create('db');
    global $db;
}
要调用数据库连接,请执行以下操作:

define('FILE_ROOT', dirname(__FILE__) . '/');
    require_once FILE_ROOT.'inc/database.php';
    open_database($factory);

    foreach ($db->query("SELECT * FROM tbl_name") as $row) { echo $row['columnName']; }
但我收到了这个错误:

致命错误:在第23行的/home/kyleport/public_html/inc/database.php中找不到类“db”

有谁能帮我解决这个问题吗?我挣扎得很厉害。

像这样使用它

new PDO('mysql:host=myHost;dbname=myDB;charset=myCharset',$user, $pass, $options_array)
在您的情况下,选项数组已经可以设置这些属性:

new PDO('mysql:host=myHost;dbname=myDB;charset=myCharset',$user, $pass,  array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false));
编辑:好的,你编辑了问题。。。 你有电话吗

return new $name( $this->connection );
在您的代码中,使用
$name='db'调用它

因此,它将执行为
返回新数据库($this->connection)

但此时显然没有名为“db”的类。

-第四个参数是选项数组。数据库名称是DSNso的一部分数据库名称在哪里@安德烈:你看到链接了吗?它向你展示了你需要如何做到这一点是的,确实如此。它就在示例1中:
$dsn='mysql:dbname=testdb;主机=127.0.0.1'你也在用你不需要的函数包装东西;您的
$provider
不需要在函数中,也不需要打开数据库()