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):
1 2 3 4 5 6 7 8 9 10 |
|
Example (incorrect usage):
1 2 3 4 5 6 7 8 9 10 |
|
Suppressing Polymorphism:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
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!