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());
as opposed to:
$var3 = globaFun($var, $var2[$anotherVar], method());
So what is the point of $this?
Additional Bonus Question:
Why do we have to differentiate static references and instances? Why do we need:
static function getValue() {
return self::value;
}
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).
Wouldn’t it be better if we had a $this that behaves like it does in Java?
Okay, so let’s remove the need for writing
$thiseverywhere. Take a look at this situation:Is
$bara local variable or a member of$foo?There has to be some differentiation. They could have allowed declaration of local variables with the
varkeyword, but that would not have been backwards-compatible and would have been very confusing to people upgrading from older versions of PHP.Same thing applies to
self::. How does the interpreter know whether the function you wanted to call is global or specific to the class?