In PHP, both self and this are used to access class properties and methods, but they serve different purposes and have distinct meanings.
self is a special identifier that refers to the current class itself and is mainly used to access static properties and static methods. It's worth noting that self is case-insensitive in PHP, so Self, SELF, or self all work.
this is a variable pointing to the current object instance, primarily used to access non-static properties and non-static methods. It can only be effectively used inside class methods.
The following example defines a class named Foo with a static property and a static method to demonstrate how to use self to access static members:
class Foo {
public static $staticProperty = "This is a static property.";
public static function staticMethod() {
echo self::$staticProperty;
}
}
Foo::staticMethod();
This code outputs:
This is a static property.
Continuing with the Foo class, this time adding a non-static property and method to show how to use this to access object members:
class Foo {
public $nonStaticProperty = "This is a non-static property.";
public function nonStaticMethod() {
echo $this->nonStaticProperty;
}
}
$foo = new Foo();
$foo->nonStaticMethod();
The output is:
This is a non-static property.
In PHP object-oriented programming, self is mainly used to access static members of the current class, while this refers to the current object instance to access non-static members. Specifically:
Understanding and properly using self and this helps write clear and maintainable PHP code.
Hope this article helps you grasp the difference and usage of self and this in PHP.