PHP equivalent to javascript "with" scope operator

Porting some code from Javascript, I have such a misunderstanding. For instance:

In javascript we can create this code.

var a, x, y; var r = 10; with (Math) { a = PI * r * r; x = r * cos(PI); y = r * sin(PI / 2); } 

Instead

 a = Math.PI * r * r; x = r * Math.cos(Math.PI); y = r * Math.sin(Math.PI / 2); 

This last example will have the same comportament in PHP, IE, in the second code example Math is redundant.

Does anyone have a solution for clean, elegant code?

I am adding the following code as a new example:

 class MyExampleClass { function example { for($i = 0; $i < count($this->Registers); $i++) { $r = "50"; $r .= $this->ZeroFill($this->numericOnly($this->Registers[$i]->Id)), 15) . $this->ZeroFill($this->numericOnly($this->Registers[$i]->Inscription), 25); $r .= $this->ZeroFill($this->Registers[$i]->Model, 2 ); $r .= $this->PadR($this->alpha($this->Registers[$i]->Date), 10 ); $this->WriteRecord( $r); } } 

In the third example, I can use temp $ var inside for an expression for $this->Registers[$i] , but if all the treatment code has become in the class, for example, in the Sanitize class.

 with (Sanitize) { $r .= ZeroFill(numericOnly($tmp), 15); // are much more clear and using OO } 

I want to make shorter and non-repeating code.

+4
source share
3 answers

What you are looking for is more akin to java than javascript, in java this qualification is optional and may be omitted. The javascript with statement is half-functional, since it doesn't even work with assignments.

PHP does not have this, and you must explicitly enter $this-> every time.

+4
source

Areas of PHP are very different from Javascript. I suggest that the best I could think of was to extend the class and use $this-> , rather than the name of the class all over the world. Do you have a use case that you could share with us?

0
source

pi () , cos () and sin () are all reserved functions in PHP

 <?php $r = 10; $a = pi() * $r * $r; $x = $r * cos(pi()); $y = $r * sin(pi() / 2); ?> 
0
source

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


All Articles