Late static binding and early binding are concepts in PHP that describe how methods or properties are resolved when a class hierarchy is involved. The key difference lies in when the resolution occurs and which class context is used.
Early Binding (self)
- Definition: Early binding resolves the method or property to the class in which it is defined, regardless of the class from which it is called.
- Behavior:
- Uses
selfto reference the class where the code is written. - The binding happens at compile time.
- Does not respect polymorphism in class hierarchies.
- Uses
Example:
Explanation:
self::who()incallWho()binds to the methodwho()inParentClassbecauseselfis resolved at compile time.- Even when
ChildClasscallscallWho(), it does not useChildClass::who().
Late Static Binding (static)
- Definition: Late static binding resolves the method or property to the class that is actually calling the method (runtime class context).
- Behavior:
- Uses
staticto reference the calling class. - The binding happens at runtime.
- Respects polymorphism in class hierarchies.
- Uses
Example:
Explanation:
static::who()incallWho()resolves to thewho()method in the calling class.- When
ChildClasscallscallWho(), it dynamically binds toChildClass::who().
Comparison Table
| Feature | Early Binding (self) | Late Static Binding (static) |
|---|---|---|
| Resolution Time | Compile time | Runtime |
| Reference Context | The class where the method is defined | The class that is calling the method |
| Polymorphism | Does not respect polymorphism | Respects polymorphism |
| Keyword Used | self | static |
| Behavior with Inheritance | Always binds to the parent class method (if called in the parent) | Dynamically binds to the calling class method |
Key Points to Consider
- Use early binding (
self) when the behavior should always be tied to the parent class and should not change with inheritance. - Use late static binding (
static) when you want polymorphic behavior, allowing the method or property resolution to adapt to the calling class at runtime.
Practical Example Comparing Both
This highlights how self locks behavior to the defining class, while static allows dynamic resolution based on the calling class.
Thank you.
No comments:
Post a Comment