沃梦达 / 编程问答 / php问题 / 正文

将 PHP 对象设置为全局?

Set a PHP object global?(将 PHP 对象设置为全局?)

本文介绍了将 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 对象设置为全局?

基础教程推荐