Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the point of having $this and self:: in PHP?

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?

like image 855
NullUserException Avatar asked Jul 27 '10 15:07

NullUserException


People also ask

What is purpose of pseudo object $this and self in PHP?

self is used to access static or class variables or methods and this is used to access non-static or object variables or methods. So use self when there is a need to access something which belongs to a class and use $this when there is a need to access a property belonging to the object of the class.

What is the purpose of $this in PHP?

$this is a reserved keyword in PHP that refers to the calling object. It is usually the object to which the method belongs, but possibly another object if the method is called statically from the context of a secondary object. This keyword is only applicable to internal methods.

What does :: mean in PHP?

In PHP, the double colon :: is defined as Scope Resolution Operator. It used when when we want to access constants, properties and methods defined at class level. When referring to these items outside class definition, name of class is used along with scope resolution operator.

What is the difference between self and $this in PHP?

The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.


2 Answers

Since this was re-opened, I'll post here my answer, as promised.

TL;DR version If it were not required to qualify a member access, there would be not only performance penalties, but the same line of code could simultaneously signify a field access and a local variable access, depending on the code path.

Full version

In PHP, there's always one symbol table active at the table. This is either the global symbol table or a function/method local symbol table (which by the way, are lazily built). Superglobals and optimizations like compiled variables aside, when a variable $var is requested, it is looked up in the current symbol table. Since the object properties live not on the symbol tables, but instead on either in the objects (the instance properties) or the structure associated the class (the static properties), a lookup for $var can never return a property.

To bring a given variable to the function scope, you must explicitly signal your intention by creating a reference. Examples:

$myglobal = 7;
class A {
    private $prop;
    public function meth() {
        global $myglobal; //bring a global to the current scope
        $prop =& $this->prop; //brings a property to the current scope
        $local = 4;
        $lambda = function () use (&$local) { };
    }
}

Obviously, this is just a more sophisticated way to phrase what currently happens. The question is why this behavior?

After all, in Java we only have to type this.prop when there's a local variable called prop hiding the property. Why is this not a good option for PHP?

I can think of several reasons.

The object properties are determined at runtime

PHP has something called "dynamic properties". You can assign new properties to objects at runtime. In fact given two objects of the same class, one can have a given property $a and while the other doesn't. Example:

$obj1 = new stdClass();
$obj2 = new stdClass();
$obj1->a = 7;

In PHP, the defined local variables are determined at runtime

Variables do not have to be declared; consequently, depending on the code path, at some point a variable may or may not be defined. To add insult to the injury, we also have the monster called "variable variables". Example:

class A {
    private $g = 3;
    public function func($varname) {
        if (rand(1,2) == 1) {
            $g = 4; //no block scope; the scope is the function's
        }
        $$varname = 5; //god knows what's happening here
        //if local variables hid properties, we'd have trouble
    }
}

In Java, a given identifier may also represent, inside the same function, a local variable and a property, but:

  • Not within the same block (in PHP, all blocks in a function share exactly the same scope).
  • You get a warning if you're hiding a property.
  • Crucially, in any given occurrence of an identifier, it's either a property or a local variable, it can't sometimes be one and other times the other.

Consequences

Owing to these facts, it would be impossible to determine at compile time if $var referred to a local variable or to a property. Consequently:

  • At runtime, every time a variable occurred, it would have to looked up first in the local symbol table, then in the instance properties table, and finally in the static properties list, or any other order (since there can't be an instance and a static property with the same name and static properties need to be declared, there would be some optimization potential here, but the point stands). This means a symbol would have, in the worst case, would have to be looked up in three different places. This is bad from a performance perspective.
  • A given symbol occurrence could mean different things on different occasions. This is a recipe for disaster.
like image 166
Artefacto Avatar answered Nov 04 '22 16:11

Artefacto


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

Is $bar a local variable or a member of $foo?

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.

Same thing applies to self::. How does the interpreter know whether the function you wanted to call is global or specific to the class?

like image 37
Sasha Chedygov Avatar answered Nov 04 '22 14:11

Sasha Chedygov