我通过PDO连接到mysql:
$instance = new PDO("mysql:host=$server;dbname=$database;", $username, $password);
我想:
这在stackoverflow上讨论,最佳答案似乎是一个很好的解决方案:How to properly set up a PDO connection
我尝试使用此代码创建与数据库的连接,但是当我加载页面时没有错误,只有白页(它不起作用):
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 );
}
}
$server = 'localhost';
$username = 'dbuser';
$password = 'password';
$database = 'mydb';
$provider = function(){
$instance = new PDO("mysql:host=$server;dbname=$database;", $username, $password);
$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
return $instance;
};
$factory = new StructureFactory( $provider );
$something = $factory->create('Something');
最后一行代码打破了php脚本,为什么会这样?如何从StackOverflow正确实现解决方案?