有没有办法重新分配$ this? [英] Is there a way to reassign $this?
问题描述
首先,我不想扩展一个类.我理想上想这样做.
First of all, I do not want to extend a class. I would ideally like to do this.
public function __construct() {
/* Set Framework Variable */
global $Five;
$this =& $Five;
}
我有一个系统,其中变量$ Five是包含其他库的容器类.我可以将其分配给五个本地变量...即
I have a system where the variable $Five is a container class which contains other libraries. I could assign this to a local variable of Five... i.e.
public function __construct() {
/* Set Framework Variable */
global $Five;
$this->Five = $Five;
}
但是,我试图避免这种情况的原因是函数调用会变得有点长.
However, the reason why I am trying to avoid this is that function calls would be getting a little long.
$this->Five->load->library('library_name');
有点难看.会更好.
$this->load->library('library_name');
什么是最好的解决方案?
What is the best solution for this?
推荐答案
我认为
$this->Five->load->library('library_name');
除非您决定让该类扩展帮助程序类,否则
将是您的最佳选择.又名
is going to be your best option unless you decide to have the class extend the helper class. AKA
class Something extends Helper_Class
但是,这意味着每次实例化类时都会实例化Helper_Class
.
However, this means that Helper_Class
is instantiated every time you instantiate a class.
另一种方法是拥有一个伪静态类,该类将所有帮助程序类分配给类成员
Another method would be to have a pseudo-static class that assigned all of the helper classes to class members
public function setGlobals($five)
{
$this->loader = $five->loader;
}
然后就叫它
public function __construct($five)
{
someClass::setGlobals($five);
}
如果$Five
是全局变量,则每次使用global $Five
时都可以,但是将其置于每个函数的顶部似乎是不好的编码.
If $Five
is a global, you could just global $Five
everytime you want to use it, but putting that at the top of every function just seems like bad coding.
此外,我只想在公共服务声明中声明全局变量通常是个坏主意,您可能想搜索依赖注入"或全局变量的替代方法.又名
Also, I'd just like to do my public service announcement that Global variables are generally a bad idea, and you might want to search 'Dependency Injection' or alternative to globals. AKA
public function __construct($five);
代替
global $five;
全局变量依赖于存在并已设置的外部变量,而依赖项注入则请求一个假定它是Five类的实例的变量.
Globals rely on an outside variable to be present and already set, while dependency injection requests a variable that it is assuming to be an instance of the Five class.
如果您正在运行PHP 5.1(感谢Gordon),则可以通过执行以下操作确保变量是FiveClass
的实例:
If you are running PHP 5.1 (Thanks Gordon), you can insure the variable is an instance of the FiveClass
by doing this:
public function__construct(FiveClass $five);
这篇关于有没有办法重新分配$ this?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!