Home >Backend Development >PHP Tutorial >PHP `self` vs. `$this`: When to Use Each?
When to Use 'Self' and '$This' in PHP
In PHP, understanding the distinction between 'self' and '$this' is crucial. 'Self' refers to the current class, while '$this' refers to the current object.
When to Use 'Self':
Accessing static members (variables or methods):
class MyClass { static $static_member = 10; } echo MyClass::$static_member; // Output: 10
Calling parent class methods:
class ChildClass extends ParentClass { public function myMethod() { self::parentMethod(); // Calls the parent class method } }
When to Use '$This':
Accessing non-static members:
class MyClass { private $instance_member = 20; } $obj = new MyClass(); echo $obj->instance_member; // Output: 20
Calling instance methods:
class MyClass { public function myMethod() { echo $this->instance_member; // Accesses the instance member } }
Polymorphism: Calling instance methods from derived classes:
class BaseClass { public function myMethod() { echo 'BaseClass::myMethod()'; } } class DerivedClass extends BaseClass { override public function myMethod() { echo 'DerivedClass::myMethod()'; } } $baseObj = new BaseClass(); $derivedObj = new DerivedClass(); $baseObj->myMethod(); // Output: 'BaseClass::myMethod()' $derivedObj->myMethod(); // Output: 'DerivedClass::myMethod()'
Suppressing polymorphism: Calling parent class methods using 'self' in derived classes:
class BaseClass { public function myMethod() { echo 'BaseClass::myMethod()'; } } class DerivedClass extends BaseClass { override public function myMethod() { parent::myMethod(); // Calls the BaseClass's myMethod() using self:: } } $derivedObj = new DerivedClass(); $derivedObj->myMethod(); // Output: 'BaseClass::myMethod()'
The above is the detailed content of PHP `self` vs. `$this`: When to Use Each?. For more information, please follow other related articles on the PHP Chinese website!