简体   繁体   English

Mysqli conn包含文件-全局变量PHP

[英]Mysqli conn include file - global variable PHP

I'm including the MySQLi connection file in the constructor of a PHP class. 我将MySQLi连接文件包含在PHP类的构造函数中。 Since I need to reach the connect variable in methods in this class I need to make the variable global. 由于需要在此类的方法中访问connect变量,因此需要使变量成为全局变量。 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
  }

}

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). 如果全局变量不好,我们将没有$_GET$_POST (它们是实际的全局变量)。

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. mysqli.php脚本创建的任何局部变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM