[英]PHP assign $this of another class
I have been wondering is it possible to assign another object to $this?我一直想知道是否可以将另一个 object 分配给 $this?
In CodeIgniter I am calling another controller from main controller.在 CodeIgniter 中,我正在从主 controller 调用另一个 controller。
application/controllers/module.php应用程序/控制器/模块.php
Class Module extends CI_Controller {
public function __construct() {
parent::__construct();
}
public function _remap($class, $args = array()) {
// doing some checks that is there a valid file, class and method
// assigning the $method.
// including MY_Module class. I'am extending every module from this class.
// then:
$EG = new $class();
call_user_func_array(array(&$EG, $method), array_slice($this->uri->rsegments, 3));
}
}
In called class:在调用 class 中:
Class Users extends MY_Module
{
public function __construct() {
parent::__construct();
}
public function index() {
// Want to use this class and method like it is a codeigniter controller.
}
}
MY_Module: MY_模块:
Class My_Module {
public function __construct() {
$this =& CI_Controller::get_instance(); // Here is problem.
}
}
I want to use instantiated class' declaretion to My_Module class.我想对 My_Module class 使用实例化类的声明。 So that it wont initialize same libraries and won't spend more resource.
这样它就不会初始化相同的库并且不会花费更多资源。
How can I accomplish that?我怎样才能做到这一点?
Thanks for advices.感谢您的建议。
EDIT: I tried to extend MY_Module from CI_Controller.编辑:我试图从 CI_Controller 扩展 MY_Module。 But since its already instantiated once, it is causing problems.
但是由于它已经实例化了一次,因此会引起问题。
You can't "inject" a reference to your current $this
object.您不能“注入”对当前
$this
object 的引用。 And even if that was possibile i would strongly advise against.即使这是可能的,我也会强烈反对。
Just assign the reference to another var and use from it.只需将引用分配给另一个 var 并从中使用。
public function __construct() {
$yourSingleton = CI_Controller::get_instance();
}
This is not possible in PHP (as it should).这在 PHP 中是不可能的(应该如此)。
You should rephrase your question into something more like this:你应该把你的问题改写成更像这样的东西:
I have two classes and both of them initialize the same libraries (thus using up more resources).
我有两个类,它们都初始化了相同的库(因此占用了更多资源)。 How can I avoid this?
我怎样才能避免这种情况?
[example here]
[此处示例]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.