Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of $this variable in PHP

Tags:

php

Why does PHP allow 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 $this variable is ignored and the call is made as if the method were on the DogeCoin class.

like image 822
Chibueze Opata Avatar asked Mar 19 '26 08:03

Chibueze Opata


1 Answers

In one sentence: $this is a reference to the current object instance.
An object is/may be composed of several things, including methods and properties of several inherited classes, traits and dynamically added members. Only the "composite" result of all inheritance and dynamic modification during runtime is what makes up the final object instance.

The actual call $this->nonDogeMember() is only resolved at runtime. Since the object it's being called on ($d) has that method (through inheritance), everything's fine.

Having said that, you should not write this kind of code, because there indeed is no guarantee that this method will exist at runtime and may produce a runtime error. To avoid this, you should define your class and that 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 to help you ensure such runtime errors won't happen, or at least they'll be caught at an earlier point in (run)time and produce an easier to trace error.

like image 151
deceze Avatar answered Mar 21 '26 22:03

deceze