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();
?>
|
Output
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. |
Learn to code easily with our course
Coding for Everyone. This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
09 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...