Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}

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');

Its a little ugly. Far better would be.

$this->load->library('library_name');

What is the best solution for this?

like image 244
JasonS Avatar asked Dec 29 '22 05:12

JasonS


2 Answers

I think that

$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

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;
}

Then just call it

public function __construct($five)
{
    someClass::setGlobals($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);

instead of

global $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.

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);
like image 75
Tyler Carter Avatar answered Jan 10 '23 16:01

Tyler Carter


$this is a reference to the current instance of the class you are defining. I do not believe you can assign to it. If Five is a global you ought to be able to just do this:

$Five->load->library('library_name');
like image 24
Daniel Bingham Avatar answered Jan 10 '23 14:01

Daniel Bingham