如何销毁 Codeigniter 库实例

vas*_*ero 3 php codeigniter instance destroy

我想知道是否有任何方法可以销毁 Codeigniter 库实例。

我想做的是这样的:

$this->load->library('my_library');
/**
    Code goes here
**/
$this->my_library->destoy_instance();
Run Code Online (Sandbox Code Playgroud)

我需要这样做的原因是因为我需要在执行大型脚本时释放 RAM 内存。

任何帮助将不胜感激。

Ark*_*ung 6

您可以通过使用unset或 setting来简单地做到这一点null

unset($this->my_library);
Run Code Online (Sandbox Code Playgroud)

或者

$this->my_library = null;
Run Code Online (Sandbox Code Playgroud)

这个答案也值得一读,让您详细了解这两种方式。

编辑

没有内置方法来销毁加载的库对象。但是你可以通过扩展Loader类来做到这一点。然后从该类加载和卸载库。这是我的示例代码..

应用程序/库/custom_loader.php

class Custom_loader extends CI_Loader {
    public function __construct() {
        parent::__construct();
    }

    public function unload_library($name) {
        if (count($this->_ci_classes)) {
            foreach ($this->_ci_classes as $key => $value) {
                if ($key == $name) {
                    unset($this->_ci_classes[$key]);
                }
            }
        }

        if (count($this->_ci_loaded_files)) {
            foreach ($this->_ci_loaded_files as $key => $value)
            {
                $segments = explode("/", $value);
                if (strtolower($segments[sizeof($segments) - 1]) == $name.".php") {
                    unset($this->_ci_loaded_files[$key]);
                }
            }
        }

        $CI =& get_instance();
        $name = ($name != "user_agent") ? $name : "agent";
        unset($CI->$name);
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的控制器中..

$this->load->library('custom_loader');
// To load library
$this->custom_loader->library('user_agent');
$this->custom_loader->library('email');

// To unload library
$this->custom_loader->unload_library('user_agent');
$this->custom_loader->unload_library('email');
Run Code Online (Sandbox Code Playgroud)

希望它会很有用。


zer*_*nes 5

好的,如果您需要在同一个控制器中重新创建同一个对象,我找到了一个解决方案。传递第三个属性的技巧,该属性是您可以分配对象的自定义名称。

$this->load->library('my_library', $my_parameters, 'my_library_custom_name');
Run Code Online (Sandbox Code Playgroud)

如果您只想取消设置对象,PHP 会处理。您可以确认在您的类上使用析构函数。

public function __destruct() {

    // do something to show you when the object has been destructed

}
Run Code Online (Sandbox Code Playgroud)