PHP 相当于 Javascript "with"作用域语句

标签 php javascript with-statement

从 Javascript 移植一些代码我遇到了这种不便。例如:

在 javascript 中我们可以生成这段代码。

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

代替

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

在最后一个示例中,PHP、IE 中的行为相同,在第二个代码示例中,Math 是多余的。

有人有任何清晰优雅代码的解决方案吗?

我正在添加以下代码作为新示例:

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);
        }
    }

在第三个示例中,我可以在 $this->Registers[$i] 的语句中使用一个临时 $var,但是如果所有处理代码都在一个类中,例如 Sanitize 类。

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

我想要一种方法来编写更短且没有重复的代码。

最佳答案

您正在寻找的是比 javascript 更类似于 java 的东西,在 java 中 this 限定是可选的,可以省略。 javascript 的 with 语句只有一半的功能,因为它甚至不能处理赋值。

PHP 没有,您每次都必须显式输入 $this->

关于PHP 相当于 Javascript "with"作用域语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13462413/

相关文章:

PHP 与 UTF8 输出到 PHPExcel?

php - 未捕获的 ReflectionException : Class log does not exist in/vendor/laravel/framework/src/Illuminate/Container/Container. php:738

javascript - 尝试设置谷歌地图信息窗口内容的问题

javascript - 如何使用 jquery 或 javascript 从字符串中查找完全不同的数字

python - 在 Python 2.5 中使用 with 语句 : SyntaxError?

php如何从头到尾替换斜杠?

javascript - 在 HTML 中打印为 <pre> 时如何用新行替换 `\n`?

javascript - 如何排序和显示目录中的 HTML 文件及其链接

python - 我可以在 python 中将 with 语句与列表一起使用吗?

python - 是否有使用 Sqlite 的 "with conn.cursor() as..."方法?