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 (!) produces some badly legible source, such as:
$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 a way to avoid $this-> everywhere?
No, it’s not possible to avoid that construct with PHP’s built-in notion of OOP.
PHP, like JavaScript, Python and Perl — but unlike Java and not always like Ruby — always requires an explicit receiver — or,
$thisfor the “current instance” — to access members. The syntax is just the form PHP happens to use to denote this construct and was likely heavily influenced by “being a late comer” to the language and having to fit it. It is also reminiscent of Perl/C syntax.While the location can be altered or the number of sites may be reducible, at the end of the day, that is the method of accessing members.
Happy coding.