Is there any way to avoid $ this-> everywhere?

I have a class with many methods and variables in PHP. Every time I need a method to call another in the same class, I have to add $this-> . This (!) Creates a poorly distinguishable source, for example:

 $nextX = $this->calculateNextX($this->DX, $this->DY, $this->DZ); $nextY = $this->calculateNextY($this->DX, $this->DY, $this->DZ); $nextZ = $this->calculateNextZ($this->DX, $this->DY, $this->DZ); $this->X = $nextX; $this->Y = $nextY; $this->Z = $nextZ; 

Is there any way to avoid $this-> everywhere?

+6
source share
3 answers

No, this construct cannot be avoided with the built-in PHP concept for OOP.

PHP, like JavaScript, Python, and Perl - but unlike Java and not always like Ruby - always requires an explicit receiver - or $this for the "current instance" - to access the elements. The syntax is just the form that PHP uses to refer to this construct, and it was probably heavily influenced by the "be late come" language and match it. It also resembles Perl / C syntax.

While the location may be changed or the number of sites may be reduced, at the end of the day it is a method of accessing members.

Happy coding.

+6
source

You can do it in every method.

 extract(get_object_vars($this)); 

Although this will allow you to get variables, not methods or static properties. And they will not be links, so they are read-only.

+2
source

You can set it to something else

 $a = $this; $a->stuff(); 

Even in C ++, I prefer to use this , although for clarity, you are acting on a member of the class. However, it is not optional in PHP.

0
source

Source: https://habr.com/ru/post/904442/


All Articles