Set a PHP object global?

前端 未结 3 1933
清酒与你
清酒与你 2020-12-11 08:41

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.

$db         


        
3条回答
  •  悲哀的现实
    2020-12-11 09:20

    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.

提交回复
热议问题