Behavior of $ this variable in PHP

Why PHP allows you to do this:

<?php

class Doge
{
    public function dogeMember()
    {
        echo "Hello From Doge\r\n";
        $this->nonDogeMember();
    }
}

class DogeCoin extends Doge
{
    public function nonDogeMember()
    {
        echo "Hello from DogeCoin\r\n";
    }
}

$d = new DogeCoin;
$d->dogeMember();

      

Apparently, from the opcode, the variable is $this

ignored and the call is made as if the method were on a DogeCoin

class.

+3


source to share


3 answers


In one sentence: $this

is a reference to an instance of the current object .
An object consists of several elements, including methods and properties of several inherited classes, traits, and dynamically added elements. Only the "composite" result of all inheritance and dynamic changes at runtime is what constitutes the final instance of the object.

The actual call $this->nonDogeMember()

is only allowed at runtime. Since the object it is called on ( $d

) has this method (via inheritance), everything is fine.

Having said that, you shouldn't write code like this, because there really is no guarantee that this method will exist at runtime and could lead to a runtime error. To avoid this, you must define your class and this method as abstract:



abstract class Doge {

    public function dogeMember() {
        echo "Hello From Doge\r\n";
        $this->nonDogeMember();
    }

    abstract public function nonDogeMember();

}

      

This is PHP's way of helping you ensure that such runtime errors will not be executed, or at least they will be caught at an earlier time (runtime) and will make it easier to track errors.

+2


source


From the manual on Late Static Bindings ΒΆ

In non-static contexts, the called class will be the class object. Since $ this-> will try to call private methods from the same scope, using static :: may give different results. Another difference is that static :: can only refer to static properties.

The tutorial follows the following example.

class A {
    public function test() {
        $this->foo();
    }
}

class B extends A {
    public function foo() {
        echo "Im in B\n";
    }
}

$c = new B();
$c->test();   
$a = new A();
$a->test();

      



Output.

Im in B
PHP Fatal error:  Call to undefined method A::foo() in ...

      

Yes, PHP allows this type of behavior. Should you use it? Not.

0


source


When you extend the Doge class, you inherit all other methods and properties. If you don't want the dogeMember () method in your child class, set both classes to extend some other class - perhaps an abstract class.

class DogeCoin
{
public function dogeMember()
{
    echo "Hello From Doge\r\n";
    $this->nonDogeMember();
}

public function nonDogeMember()
{
    echo "Hello from DogeCoin\r\n";
}
}

      

0


source







All Articles