Home >Backend Development >PHP Tutorial >通过函数返回引用来对类的属性初始化时,出现错误 "No database selected"

通过函数返回引用来对类的属性初始化时,出现错误 "No database selected"

WBOY
WBOYOriginal
2016-06-06 20:38:441049browse

<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"
而当我在类外面使用时,程序运行正常。
错误在哪里?

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn