When to Use 'self' over '$this' in PHP 5
In PHP 5, using the correct keyword to refer to class members and methods is crucial. When it comes to the choice between 'self' and '$this', the decision depends on whether you're referencing a static member or an instance member.
Using '$this' for Instance Members
'$this' refers to the current instance of the object. It is used to access non-static members, which are specific to each instance. For example:
class MyClass { private $member = 1; function __construct() { echo $this->member; // Outputs 1 } }
Using 'self' for Static Members
'self' refers to the current class, regardless of the instance. It is used to access static members, which are shared among all instances of the class. For example:
class MyClass { private static $staticMember = 2; function __construct() { echo self::$staticMember; // Outputs 2 } }
Polymorphism and Member Functions
'$this' enables polymorphism, allowing derived classes to override member functions of the parent class. For example:
class BaseClass { function foo() { echo 'BaseClass::foo()'; } } class DerivedClass extends BaseClass { function foo() { echo 'DerivedClass::foo()'; } } $derivedObject = new DerivedClass(); $derivedObject->foo(); // Outputs 'DerivedClass::foo()'
Suppressing Polymorphism with 'self'
By using 'self' instead of '$this' in member functions, you can suppress polymorphic behavior. The function will always call the implementation from the parent class, regardless of the object's actual type. For example:
class BaseClass { function foo() { echo 'BaseClass::foo()'; } } class DerivedClass extends BaseClass { function foo() { echo 'DerivedClass::foo()'; } } $derivedObject = new DerivedClass(); $derivedObject->self::foo(); // Outputs 'BaseClass::foo()'
The above is the detailed content of When to Use `self` vs. `$this` in PHP 5 to Access Class Members?. For more information, please follow other related articles on the PHP Chinese website!