Home >Backend Development >PHP Tutorial >PHP 5: `$this` vs. `self` – When to Use Each?
Self vs. $this: When and How to Use Each
Question:
In PHP 5, how do the keywords "self" and "$this" differ in their usage? When should each be used appropriately?
Answer:
Short Answer:
Use "$this" to refer to the current object's instance variables and methods. Use "self" to refer to the current class's static variables and methods.
Full Answer:
Non-Static vs. Static Members:
Polymorphism:
Example (correct usage):
class X { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo $this->non_static_member . ' ' . self::$static_member; } } new X(); // Output: 1 2
Example (incorrect usage):
class X { private $non_static_member = 1; private static $static_member = 2; function __construct() { echo self::$non_static_member . ' ' . $this->static_member; // Incorrect usage } } new X(); // Error: Undefined properties
Suppressing Polymorphism:
class X { function foo() { echo 'X::foo()'; } function bar() { self::foo(); // Suppresses polymorphism } } class Y extends X { function foo() { echo 'Y::foo()'; } } $x = new Y(); $x->bar(); // Output: X::foo()
Summary:
Use "$this" for non-static member access and polymorphism. Use "self" for static member access and when you need to suppress polymorphism.
The above is the detailed content of PHP 5: `$this` vs. `self` – When to Use Each?. For more information, please follow other related articles on the PHP Chinese website!