Rishi Raj G. answered 09/28/24
Computer Science - Technology/Engineering and Business Consultant
$this refers to the current instance of the class. It’s used when you want to access instance members (properties and methods) of the class. It can only be used in non-static methods since it refers to an object of the class.
e.g. class MyClass {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name; // Accessing the instance property via $this
}
}
$object = new MyClass('John');
echo $object->getName(); // Output: John
In this example, $this->name refers to the name property of the specific instance of MyClass.
self refers to the current class itself. It’s used to access static members (properties and methods) of the class or to reference constants and static methods. self cannot be used to refer to instance members since it doesn't operate on the object level but on the class level. You use self to refer to static properties and methods.
class MyClass {
public static $type = 'Human';
public static function getType() {
return self::$type; // Accessing the static property via self
}
}
echo MyClass::getType(); // Output: Human
Here, self::$type refers to the static property type of the class MyClass.