0
嘿家伙我有一个连接类,我找到了pdo。我在包含该文件的页面上调用连接方法。问题是在函数内$ conn变量没有被定义,即使我声明方法是公开的(对我来说是裸机,我对OOP很陌生),我想知道是否有人有一个优雅的解决方案,然后在每个函数中使用全局。任何建议,非常感谢。php pdo连接范围
CONNECTION
class PDOConnectionFactory{
// receives the connection
public $con = null;
// swich database?
public $dbType = "mysql";
// connection parameters
// when it will not be necessary leaves blank only with the double quotations marks ""
public $host = "localhost";
public $user = "user";
public $senha = "password";
public $db = "database";
// arrow the persistence of the connection
public $persistent = false;
// new PDOConnectionFactory(true) <--- persistent connection
// new PDOConnectionFactory() <--- no persistent connection
public function PDOConnectionFactory($persistent=false){
// it verifies the persistence of the connection
if($persistent != false){ $this->persistent = true; }
}
public function getConnection(){
try{
// it carries through the connection
$this->con = new PDO($this->dbType.":host=".$this->host.";dbname=".$this->db, $this->user, $this->senha,
array(PDO::ATTR_PERSISTENT => $this->persistent));
// carried through successfully, it returns connected
return $this->con;
// in case that an error occurs, it returns the error;
}catch (PDOException $ex){ echo "We are currently experiencing technical difficulties. We have a bunch of monkies working really hard to fix the problem. Check back soon: ".$ex->getMessage(); }
}
// close connection
public function Close(){
if($this->con != null)
$this->con = null;
}
}
PAGE用在
include("includes/connection.php");
$db = new PDOConnectionFactory();
$conn = $db->getConnection();
function test(){
try{
$sql = 'SELECT * FROM topic';
$stmt = $conn->prepare($sql);
$result=$stmt->execute();
}
catch(PDOException $e){ echo $e->getMessage(); }
}
test();
你可以给我看一个例子吗? – Scarface 2010-05-25 00:38:35
@Scarface:下载TinyMVC框架并从插件文件db.PDO_MVC.php获取你有例子 – Svisstack 2010-05-25 09:01:02