PHP-返回MySQLi对象形式__construct方法


PHP - Returning MySQLi Object form __construct method

我有一个Connection类,看起来像:

class Connection{
    private $link;
    public function __construct(){
        $this->link = new mysqli("localhost","root","","myDatabase");
        return $this->link;
    }
    public function __destruct(){
        $this->link->close();
    }
}

我正在努力做到这一点:

$link = new Connection();
$sql = "SELECT * FROM `events`";
$query = mysqli_query($link,$sql);
//Some stuff heref
$link->__destruct();

这是无效的吗?我得到以下错误:

警告:mysqli_query()要求参数1为mysqli

警告:mysqli_query()要求参数1为mysqli

这是因为$link实际上不是mysqli的实例;它是CCD_ 4的一个实例。

不能从__construct()返回任何内容,因为它的目的只是构建Connection类本身的实例,而不是作为其他类的工厂。return $this->link没有达到您的预期效果。

你有几个选择。

您可以使您的类extend mysqli,其中您主要只是对凭据进行硬编码并用它们调用parent::__construct(),这完全消除了对__destruct()的需要:

// Merely extends mysqli, hard-coding your credentials
class Connection extends mysqli{
    // Your constructor has no params, and internally calls
    // the parent constructor
    public function __construct(){
        parent::__construct("localhost","root","","myDatabase");
    }    
}

你为使用它编写的代码会立即工作,但没有太多附加值,我不认为这真的是你想要的。

更好的选择:

如果你想创建一个存储和管理mysqli对象的类,你可以实例化它,但不能返回它。你需要创建一个方法来返回它。

class Connection{
    private $link;
    // The constructor instantiates the mysqli
    public function __construct(){
        $this->link = new mysqli("localhost","root","","myDatabase");
    }
    // Other methods can operate on or manage the mysqli instance
    public function __destruct(){
        $this->link->close();
    }
    // Public accessor method to return the connection
    public function getConnection() {
        return $this->link;
    }
}

然后调用该方法来检索连接。

$link = new Connection();
$sql = "SELECT * FROM atable";
// Call getConnection() to get the actual link
$query = mysqli_query($link->getConnection(), $sql);
$link->__destruct();

您应该执行以下操作:

<?php
class Connection{
    private $link;

    public function __construct(){
        $this->link = new mysqli("localhost","root","","myliveca_baikalpik");
    }
    public function connect(){
        return $this->link;
    }

}
$con = new Connection();
$link = $con->connect();

$sql = "SELECT * FROM `events`";
$query = mysqli_query($link,$sql);
//Some stuff heref
$link->close();

注意:__construct方法默认返回null。你需要什么返回的是MySQLi对象。

__construct中的Return是无用的,因为new运算符总是返回给定类的实例。

若要创建类的实例,必须使用new关键字。一对象将始终被创建,除非该对象具有构造函数定义,在出现错误时引发异常。

http://php.net/manual/en/language.oop5.basic.php#language.oop5.basic.new

另外,尽量避免直接调用魔术方法。