PHP class 对象变量用法

PHP class object variable usage

我正在尝试将对象作为参数传递给 class 中的构造函数,例如:

class godtoolkit{
    protected $var;
    public $explanation;

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

    public function armageddon(){
        $this -> var -> close();
        $this -> explanation = "The World Ended!";
        return true;
    }
}

$goddemands = new godtoolkit($mysqli); // $mysqli is a normal mysqli connection
if($goddemands -> armageddon()){ // Is this closing my database?
    echo($goddemands -> explanation);
}

代码示例中的问题很明显,请记住,这是一个示例片段,但会准确询问我需要什么。

是的,调用 armageddon() 将关闭在 class.

的构造函数中传递的 mysqli 连接

简短: 是的,这将关闭 MySQLi 连接。

原因: 重要的是要注意,在 PHP 中,对象 总是 通过引用传递。也就是说,这个变量其实是一个link到内存space表示那个对象,那个变量的值走到哪里,总会指向内存中同一个space ,因此,相同的对象。

示例:

下面说明了按副本传递、按引用传递之间的区别以及对象的工作方式:

function copy_increment($int) {
    $int++;
}

function reference_increment(&$int) {
    $int++;
}

function object_increment($object) {
    $object->int++;
}

function maybe_destroy($object) {
    unset($object);
}

$object = new StdClass();
$object->int = 1;
$int_val = 1;

var_dump($int_val); // 1

copy_increment($int_val);  // Not passed by reference

var_dump($int_val); // 1

reference_increment($int_val); // Passed by reference

var_dump($int_val); // 2

var_dump($object); // int = 1

object_increment($object); // Always passed by reference

var_dump($object); // int = 2

// But here you can see that the parameters are
// still copies, but copies of the pointer and 
// un-setting only effects the current scope.
maybe_destroy($object); 

var_dump($object); // int = 2

您可以在实际操作中看到这一点 here。这对你来说意味着什么?这意味着,是的,当您传递 MySQLi 连接并存储它,然后关闭它时,它总是会关闭该对象的所有副本。

这里有一个问题,你 可以 克隆对象,但 MySQLi 就是他们所说的 "un-clone-able object," 如果你尝试它会杀死你的应用程序.. .:-(

注意: MySQLi 连接不会"need" 显式关闭,连接将在对象被销毁时终止(在应用程序结束时或在垃圾收集期间),因此您永远不必在其上显式调用关闭。

另一种选择是拥有一个工厂 class 或按需建立连接的函数。将此对象传递给构造函数,并将唯一连接存储在此对象上。我无法立即想到为什么这会有用,但设置起来相当容易,并且可以让你整天关闭连接。 ;-)

但实际上,您不需要手动关闭它,尤其是在您刚开始时。