In PHP, $this is a special variable used inside a class to refer to the current instance of the class. It is used to access the properties and methods of the current object.

Key Uses of $this

  1. Accessing Properties

    You can use $this to access the properties of the current object.

      <?php
    class Car {
        public $make;
        public $model;
    
        public function __construct($make, $model) {
            $this->make = $make;
            $this->model = $model;
        }
    
        public function displayInfo() {
            echo "Make: " . $this->make . ", Model: " . $this->model;
        }
    }
    
    $car = new Car("Toyota", "Corolla");
    $car->displayInfo(); // Outputs: Make: Toyota, Model: Corolla
    ?>
      
  2. Calling Methods

    You can use $this to call other methods within the same class.

      <?php
    class Calculator {
        public function add($a, $b) {
            return $this->calculateSum($a, $b);
        }
    
        private function calculateSum($a, $b) {
            return $a + $b;
        }
    }
    
    $calc = new Calculator();
    echo $calc->add(5, 10); // Outputs: 15
    ?>
      
  3. Chaining Methods

    You can use $this to return the current instance from a method, allowing for method chaining.

      <?php
    class Person {
        private $name;
    
        public function setName($name) {
            $this->name = $name;
            return $this; // Return current instance
        }
    
        public function getName() {
            return $this->name;
        }
    }
    
    $person = new Person();
    echo $person->setName("Alice")->getName(); // Outputs: Alice
    ?>
      
  4. Accessing the Current Instance

In object-oriented programming, $this is essential for interacting with the current object instance, especially within methods, constructors, and when accessing or modifying instance properties and methods.

Key Points

  • Instance Reference: $this refers to the current instance of the class.
  • Property and Method Access: Use $this to access or modify properties and call methods within the same object.
  • Method Chaining: Return $this from methods to enable chaining of method calls.