Set a PHP object global?(将 PHP 对象设置为全局?)
问题描述
我刚刚开始将我的项目从 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 对象设置为全局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 PHP 对象设置为全局?
基础教程推荐
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 使用 PDO 转义列名 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01