1

目前我正在这样做:

function __construct( $mysqli_connection )
{
    if( ! empty($mysqli_connection) && is_object($mysqli_connection) && ! $mysqli_connection->connect_error )
    {
        //Make the $mysqli universal to the class equal the given connection
        $this->mysqli = $mysqli_connection;
    }
    else
    {
        die("An invalid MySQLi connection was given.\n");
    }

}//function __construct

并通过以下方式启动课程:

new className( $mysqli );

它工作正常,但在我看来:

  • 多余的代码是不必要的
  • 用于占用 MySQLi 资源的内存最终翻了一番(一个在类的内存中,但在主代码中还有一个)

我的上述观点是否属实,如果是这样,是否有更好的方法从类中使用 MySQLi 资源?上述方法是我通过搜索找到的唯一方法。

4

1 回答 1

3

First of all, your code can be reduced to:

private $mysqli;

function __construct(mysqli $conn)
{
    $this->mysqli = $conn;
}

Your class shouldn't have to worry about whether the connection was established, it should be able to assume that it is. Also, type hints help to indicate what class is expected when the constructor is called.

Second, the mysqli object is not duplicated when you're using it inside another object; instead, its reference count is increased. Once the count drops to zero the object gets removed. If an object was always copied, doing dependency injection would become very expensive.

于 2013-02-15T04:57:47.250 回答