What is Php Self keyword?
self keyword is used to access the current class itself.
Difference between self and this keyword.
(i) $this keyword to refer to the current object. self keyword to refer to the current class.
(ii) $this->member for non-static members, self::$member for static members.
self keyword refer to the current class
Example:- In this eg. we define two classes student and Year both has same method name whichClass(), Student class inherited in the Year class then we create a object and call the method sayClassName() which is defined in the Student class and it has self keyword. when this method call then it call current class method(whichClass()).
<?php
class Student {
public function whichClass() {
echo "I am in MCA!";
}
/* This method has been changed to use the
self keyword instead of $this
*/
public function sayClassName() {
self::whichClass();
}
}
class Year extends Student {
public function whichClass() {
echo "I am in MCA first year!";
}
}
$yearObj = new Year();
$yearObj -> sayClassName();
?>
Output:- I am in MCA!
this keyword refer to the current object
Example:- In this eg. we define two classes student and Year both has same method name whichClass(), Student class inherited in the Year class then we create a object and call the method sayClassName() which is defined in the Student class and it has this keyword. when this method call then it call current Object, method(whichClass()).
<?php
class Student {
public function whichClass() {
echo "I am in MCA!";
}
/* This method has been changed to use the
$this keyword instead of self
*/
public function sayClassName() {
$this->whichClass();
}
}
class Year extends Student {
public function whichClass() {
echo "I am in MCA first year!";
}
}
$yearObj = new Year();
$yearObj -> sayClassName();
?>
Output:- I am in MCA first year!
self keyword for static variable
this keyword is not work for static variable and method then we use self keyword.
<?php
class stuClass {
public static $stu_name="ramesh";
public static $stu_rollno="Btech";
public static function display() {
echo self::$stu_name.' in '.self::$stu_rollno;
}
}
$sc=new stuClass;
$sc->display();
?>
Output:- ramesh in Btech