gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 23:07:29 25 4
gpt4 key购买 nike

从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com