$this in PHP OOP with Example

What is the $this in PHP OOP with Example?

In the OOP of PHP, there is a pseudo-variable called $this that refers to the current object. This pseudo-variable allows you to access the properties and methods of the current object within the class.

Use and Example of the PHP $this

In the code given in the following image, you can see there is a variable called $name whose value is 'John', and we try to access this variable inside the showName function.

But you can’t access like the following code, it does not work.

PHP oop Wrong way to access variable inside a method

Now I will show you two ways to access the $name property inside the showname method.

First way to access the $name property

As we all know that, If you want to access the methods and properties of a class, first you have to create an instance or object of the class.

As you can see in the following code that we have created an instance $obj of the MyClass and we have passed the name through argument $obj->showName($obj->name).

<?php
class MyClass{
    public $name = 'John';

    public function showName($x){
        echo $x;
    }
}

$obj = new MyClass();

$obj->showName($obj->name);

Second way to access the $name property

Now we will use $this to access the $name property.

As you have already read in the above that $this refers to the current object, therefore you can access the $name property through the $this, but you have to use the object operator (->) with the $this.

<?php
class MyClass{
    public $name = 'John';

    public function showName(){
        echo $this->name;
    }
}

$obj = new MyClass();

$obj->showName();

Proof – current object and $this are equal

The current object and $this are equal, because the $this refers or pointing to the current object.

<?php
class MyClass{
    public $name = 'John';

    public function x(){
        return $this;
    }
}

$obj = new MyClass();

var_dump($obj === $obj->x());
bool(true)

Access methods using $this

You can also access the current object methods using the $this.

In the following given code you can see we accessing the process() method inside the addTwo() method using the $this.

<?php
class MyClass{
    private $num = 2;

    public function process(int $x){
        return $this->num + $x;
    }

    public function addTwo(int $x){
        // Accessing the process method using $this
        echo $this->process($x);
    }

}

$obj = new MyClass();

$obj->addTwo(5);
7