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.
self operator: 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
$this operator: $this, as the ‘$’ sign suggest, 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;
When to use self over $this in PHP:
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(); ?> |
Name : GFG Age : 18
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. |