Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

pdo - Set a PHP object global?

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 ...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
       }
   }
}

You should do that instead:

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
       }
   }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...