Question

Porting some code from Javascript i'm having this incovenience. For example:

In javascript we can produce 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);

In this last example will be the same comportament in PHP, IE, in second code example Math is redundant.

Someone have any solution for a clear an elegant code?

I'm adding the following code as 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 third example I can use a temp $var inside for statement for $this->Registers[$i], but if all treatment code are became in a class like class Sanitize.

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

I want an way to do an shorter and no repetitive code.

Was it helpful?

Solution

What you are looking for is more akin to java than javascript, in java this qualification is optional and can be left out. The javascript's with statement is half functional as it doesn't even work with assignments.

PHP doesn't have that and you have to explicitly type out $this-> every time.

OTHER TIPS

PHP scopes are very different than Javascript. I suppose the best I could think of is extend a class and using $this-> rather than the class name everywhere - Do you have a use case you could share with us?

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

<?php
$r = 10;
$a = pi() * $r * $r;
$x = $r * cos(pi());
$y = $r * sin(pi() / 2);
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top