0

I'm really sick of typing $this->database or $this->otherVarOrFunc every time I call something in my controller/model/wherever else.
Is there some sort of OOP trick to have for example $database instead of $this->database in every function of my controller?

I have well defined structure of BaseController on MVC level and BaseObject for everything else class related. These two contains 5 to 20 object variables (depends on app size ) and I would be much more satisfied if typing $this-> wasnt required.

Does it have negative impact on overall performance?
Thanks in advance

Vladimir
  • 388
  • 1
  • 13

1 Answers1

0

At the beginning of each class function, you could define a local variable for the function that references to the $this.

For example:

class a {
    function __construct() {
        $this->aa = "hey";      
    }
    public $aa;
    public function aaa() {
        $ab = &$this->aa;
        $this->aa = "hey1";
        echo $ab;
    }
}
$b = new a;
$b->aaa();


Now throughout the function, use $ab instead of $this->aa

Aryeh Beitz
  • 1,974
  • 1
  • 22
  • 23
  • Well, sure, but it requires to write 1 more line per function per variable. I'm not really sure whether it'll speed proceess up... – Vladimir Aug 21 '16 at 06:26
  • I don't think using references would slow anything down, but it saves you from typing the `$this->` each tme – Aryeh Beitz Aug 21 '16 at 06:40
  • You're right! I have additional question: If I inicialize new objects from class with $this->database and counstruct of new object has ($database) as parameter, should I go for $obj = new someObject($db) or new someObject(&$db)? What should be faster and by how much? – Vladimir Aug 21 '16 at 07:01
  • It seems you don't gain performance by passing a reference. see [here](http://stackoverflow.com/a/3845530/3548935). – Aryeh Beitz Aug 21 '16 at 07:53
  • In new php versions, instances are passed to functions by reference by default. – Tomáš Jacík Aug 30 '16 at 10:18