Set a PHP object global?

前端 未结 3 1926
清酒与你
清酒与你 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:06

    You'll use $GLOBALS['dbh_pdo'] instead of $dbh_pdo inside any functions. Or you can use the global keyword, and use $dbh_pdo (i.e. global $dbh_pdo).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-11 09:30

    You could also try using a Singleton to pass back a PDO object to you. That way you only ever have one PDO object (and one database connection) in any request which saves on memory/server resources.

    0 讨论(0)
提交回复
热议问题