Search code examples
phpglobal-variablesclass-constructors

Mysqli conn include file - global variable PHP


I'm including the MySQLi connection file in the constructor of a PHP class. Since I need to reach the connect variable in methods in this class I need to make the variable global. I always heard global variables are bad. So I wonder, is this the only/best way to deal with this?

class CheckUser {

  function __construct() {
     require_once('mysqli.php');
  }

  function checkEmail($email) {
     // sql code here
  }

}

Solution

  • That's just a meme. (And dependency injection is coming right up...)

    Your connection handle is a central resource. Use it as such. A global variable is perfectly fine and the intended langauge construct for that. It makes sense as long as you only have one database / connection.

    If global variables were bad, we wouldn't have $_GET and $_POST (which are actual global variables).

    Should your class (guessing here) be the central access point to database queries, then keeing the handle as simple property is just as cromulent.

      function __construct() {
         require_once('mysqli.php');
         $this->db = $db;
      }
    

    Or whatever local variable the mysqli.php script created.