Home >Backend Development >PHP Tutorial >通过函数返回引用来对类的属性初始化时,出现错误 "No database selected"
<code>php</code><code><?php //function.php function &connectdb() { global $DBname,$DBusername,$DBpassword,$servername; $conn=new mysqli($servername, $DBusername, $DBpassword, $DBname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $conn->query("SET NAMES 'UTF8'"); return $conn; } ?> </code>
<code>php</code><code><?php /** * */ class Bar { private $conn; function __construct() { require './function.php'; $this->conn=connectdb(); $result=$this->conn->query("SELECT * FROM 15_spring_new WHERE 1;"); var_dump($this->conn->error); } } $bar = new Bar; ?> </code>
发现只要在函数中调用,就会出现这个问题。
该错误输出为:"No database selected"
而当我在类外面使用时,程序运行正常。
错误在哪里?
<code>php</code><code><?php //function.php function &connectdb() { global $DBname,$DBusername,$DBpassword,$servername; $conn=new mysqli($servername, $DBusername, $DBpassword, $DBname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $conn->query("SET NAMES 'UTF8'"); return $conn; } ?> </code>
<code>php</code><code><?php /** * */ class Bar { private $conn; function __construct() { require './function.php'; $this->conn=connectdb(); $result=$this->conn->query("SELECT * FROM 15_spring_new WHERE 1;"); var_dump($this->conn->error); } } $bar = new Bar; ?> </code>
发现只要在函数中调用,就会出现这个问题。
该错误输出为:"No database selected"
而当我在类外面使用时,程序运行正常。
错误在哪里?