問題描述
我剛剛開始將我的項目從 mysql 切換到 PDO.在我的項目中,或多或少在程序開始時創建了一個新的 PDO 對象.
I just started switching my project form the mysql to PDO. In my project a new PDO Object is created more or less right a the beginning of the programm.
$dbh_pdo = new PDO("mysql:host=$db_url;dbname=$db_database_name", $db_user, $db_password);
現在我想在一些函數和類中使用這個處理程序(這是正確的名稱嗎?).有沒有辦法讓對象像變量一樣全局化,或者我是否在嘗試一些難以言喻的愚蠢行為,因為我在網上搜索時找不到任何東西......
Now I would like to use this handler (is that the correct name?) in some functions and classes. Is there a way to make objects global just like variables or am I trying something unspeakably stupid, because I couldn't find anything when searching the web ...
推薦答案
是的,您可以像任何其他變量一樣使對象全局化:
Yes, you can make objects global just like any other variable:
$pdo = new PDO('something');
function foo() {
global $pdo;
$pdo->prepare('...');
}
您可能還想查看單例模式,它基本上是一種全局的、面向對象的樣式.
You may also want to check out the Singleton pattern, which basically is a global, OO-style.
話雖如此,我建議您不要使用全局變量.在調試和測試時,它們可能會很痛苦,因為很難分辨誰修改/使用/訪問了它,因為一切都可以.它們的使用通常被認為是一種不好的做法.考慮稍微審查一下您的設計.
That being said, I'd recommend you not to use globals. They can be a pain when debugging and testing, because it's hard to tell who modified/used/accessed it because everything can. Their usage is generally considered a bad practice. Consider reviewing your design a little bit.
我不知道您的應用程序是什么樣子,但假設您正在這樣做:
I don't know how your application looks like, but say you were doing this:
class TableCreator {
public function createFromId($id) {
global $pdo;
$stmt = $pdo->prepare('SELECT * FROM mytable WHERE id = ?');
$stmt->execute(array($id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
// do stuff
}
}
}
你應該這樣做:
class TableCreator {
protected $pdo;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
}
public function createFromId($id) {
$stmt = $this->pdo->prepare('SELECT * FROM mytable WHERE id = ?');
$stmt->execute(array($id));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
// do stuff
}
}
}
因為這里的 TableCreator
類需要一個 PDO 對象才能正常工作,所以在創建實例時傳遞一個給它是非常有意義的.
Since the TableCreator
class here requires a PDO object to work properly, it makes perfect sense to pass one to it when creating an instance.
這篇關于將 PHP 對象設置為全局?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!