在PHP中拥有$ this和self ::有什么意义? [英] What is the point of having $this and self:: in PHP?
问题描述
为什么PHP要求您显式编写$this
?我会理解您是否必须在此处使用$this
Why does PHP require you to explicitly write $this
? I would understand if you had to use $this
here:
function foo($bar) {
$this->bar = $bar;
}
但是您必须使用如下所示的冗长代码显式地编写它:
But you must write it explicitly in verbose code that looks like this:
$this->var3 = globalFun($this->var, $this->var2[$this->anotherVar], $this->method());
相对于:
$var3 = globaFun($var, $var2[$anotherVar], method());
那么$this
的意义是什么?
为什么我们必须区分静态引用和实例?我们为什么需要:
Why do we have to differentiate static references and instances? Why do we need:
static function getValue() {
return self::value;
}
如果有问题的变量/方法是静态的,PHP是否无法在运行时查找?现在,如果我想将方法从静态更改为非静态,则必须将所有self::
替换为$this->
(反之亦然).
Can't PHP find out at runtime if the variable/method in question is static? Now if I want to change a method from static to non-static, I have to replace all those self::
with $this->
(and vice-versa).
如果我们的$this
表现得像Java一样好吗?
Wouldn't it be better if we had a $this
that behaves like it does in Java?
推荐答案
好的,让我们无需在任何地方编写$this
.看一下这种情况:
Okay, so let's remove the need for writing $this
everywhere. Take a look at this situation:
class Foo {
public function setBar($value) {
$bar = $value;
}
}
$foo = new Foo();
$foo->setBar('some value');
$bar
是局部变量还是$foo
的成员?
Is $bar
a local variable or a member of $foo
?
必须有所区别.他们本可以允许使用var
关键字声明局部变量,但是这并不能向后兼容,而且对于从旧版本的PHP升级的人们会造成极大的困扰.
There has to be some differentiation. They could have allowed declaration of local variables with the var
keyword, but that would not have been backwards-compatible and would have been very confusing to people upgrading from older versions of PHP.
self::
同样适用.解释器如何知道您要调用的函数是全局的还是特定于该类的?
Same thing applies to self::
. How does the interpreter know whether the function you wanted to call is global or specific to the class?
这篇关于在PHP中拥有$ this和self ::有什么意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!