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

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

WBOY
Release: 2016-06-06 20:38:44
Original
1051 people have browsed it

<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>
Copy after login
Copy after login
<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>
Copy after login
Copy after login

发现只要在函数中调用,就会出现这个问题。
该错误输出为:"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>
Copy after login
Copy after login
<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>
Copy after login
Copy after login

发现只要在函数中调用,就会出现这个问题。
该错误输出为:"No database selected"
而当我在类外面使用时,程序运行正常。
错误在哪里?

Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template