Open In App

What is the difference between self and $this ?

Last Updated : 11 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The keyword self is used to refer to the current class itself within the scope of that class only whereas, $this is used to refer to the member variables and function for a particular instance of a class.

PHP self operator: The self operator represents the current class and thus is used to access class variables or static variables because these members belong to a class rather than the object of that class.

Syntax:

self::$static_member

PHP $this operator: The $this, as the ‘$’ sign suggests, is an object. $ This represents the current object of a class. It is used to access non-static members of a class.

Syntax:

$that->$non_static_member;

Example:

PHP




<?php
    class StudentDetail{
   
        public $name;
        public static $age;
 
        public function getName() {
            return $this->name;
        }
      
        public static function getAge() {
            return self::$age;
        }
         
        public function getStudentAge() {
            return self::getAge();
        }
    }
     
    $obj = new StudentDetail();
 
    $obj->name = "GFG";
 
    StudentDetail::$age = "18";
 
    echo "Name : " .$obj->getName()."\xA";
    echo "Age  : " .StudentDetail::getStudentAge();
 
?>


Output

Name : GFG
Age  : 18

To know When to use self over $this in PHP? you can check the attached article.

Difference between self and $this:

self

$this

The self keywоrd is nоt рreсeded by аny symbоl, we can use it as it is. this keyword should be antecedent with a $ symbol whenever referring to the class members.
In order to access class variables and methods, a scope resolution operator is used. In order to access class variables and methods, an arrow operator ( -> ) is used.
The self keyword is used to access the static members of the class present in the program. $this is used to access the non-static members of the class present in the program.
Self keyword refers to the class members, but doesn’t point toward any particular object of the class.   $this could refer to the member variables and function for a selected instance of the class.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads