In PHP 5, self
and $this
are used to access class members (properties and methods), but they have different purposes and usage contexts:
self
:self
is a keyword used to refer to static members (properties and methods) within a class.- It's used to access class-level members that are not tied to a specific instance of the class.
- You typically use
self
within the class definition itself, to access static properties and call static methods.
$this
:$this
is a variable used to refer to instance members (properties and methods) within a class.- It's used to access instance-level members, which are specific to each object created from the class.
- You use
$this
within class methods to refer to instance properties and call instance methods.
Here's an example that illustrates the difference:
php
class MyClass {
public static $staticProperty = "Static Property";
public $instanceProperty = "Instance Property";
public static function staticMethod() {
// Using 'self' to access a static property
return self::$staticProperty;
}
public function instanceMethod() {
// Using '$this' to access an instance property
return $this->instanceProperty;
}
}
// Accessing static property and method using 'self'
echo MyClass::$staticProperty . "\n"; // Output: "Static Property"
echo MyClass::staticMethod() . "\n"; // Output: "Static Property"
// Creating an instance of MyClass
$obj = new MyClass();
// Accessing instance property and method using '$this'
echo $obj->instanceProperty . "\n"; // Output: "Instance Property"
echo $obj->instanceMethod() . "\n"; // Output: "Instance Property"
In this example:
self::$staticProperty
andself::staticMethod()
are used to access static members within the class, which don't depend on object instances.$this->instanceProperty
and$this->instanceMethod()
are used to access instance members, which are specific to individual objects created from the class.
In PHP 5, you should use self
for static members and $this
for instance members based on the context in which you need to access class members. Starting from PHP 7, you can also use ::class
to reference the class name, which can be useful for resolving class names in a more dynamic way.
Comments
Post a Comment