PHP Tutorials

PHP this Keyword: How to Use $this in Classes

Learn how the PHP this keyword refers to the current object, so you can access properties and call methods inside your classes.

Serhat ALPASLAN2 min read

PHP

PHP this

The “this” keyword is used to access the properties and methods defined in a class. The PHP this keyword represents the object that is currently running. The “this” keyword is used to access the properties and methods defined in a class. For example:

class Araba {
    public $renk;
    public $hiz;
    public $model;
    
    public function ileriGit() {
        $this->hiz += 10;
    }
}

In this class, the car’s speed property is increased inside the ileriGit method using the this keyword. Because the speed property is operated on the car object this way, it changes only for that object.

In addition, the PHP this keyword can also be used to call methods defined in a class. For example:

class Araba {
    public function ileriGit() {
        // code needed for the car to move forward
    }
    
    public function arabaHareketEt() {
        $this->ileriGit();
    }
}

In this class, the ileriGit() method is called with the this keyword inside the arabaHareketEt() method. This way, when the arabaHareketEt() method is called, the ileriGit() method will also be called automatically.

Since the “this” keyword is used to access the properties and methods defined in a class, it can be used to control and change the properties and methods of the object running inside the class. This makes the code more readable and understandable.

 

  1. PHP.net’s official documentation: https://www.php.net/manual/en/language.oop5.basic.php
  2. W3Schools PHP OOP Tutorials: https://www.w3schools.com/php/php_oop.asp

Share it if it helped

Write a comment