PHP OOP Static Methods
⚡ PHP OOP – Static Methods
✔ You can call it without creating an object
✔ Use the keyword static
✔ Access using ClassName::methodName()
🟦 1️⃣ Basic Static Method Example
🟩 2️⃣ Static Method Inside Class
You can still call static methods from inside the class using self::.
🟧 3️⃣ Static Method with Parameters
🟥 4️⃣ Static Method vs Object Method
| Type | Called By | Use |
|---|---|---|
| Static Method | ClassName::method() |
Utility functions, helpers |
| Object Method | $object->method() |
When data belongs to object |
🟨 5️⃣ Static Methods Cannot Use $this
❌ This will cause an error:
🟫 6️⃣ Calling Static Methods from Child Classes (Inheritance)
🟪 7️⃣ Overriding Static Methods in Child Class
🟦 8️⃣ Late Static Binding (Important)
Use static:: when you want the child class’s static method/property.
🟩 9️⃣ Real-Life Example – Helper Class
🟧 1️⃣0️⃣ Real-Life Example – DB Connection (Singleton Pattern)
🎯 Summary (Easy to Remember)
| Feature | Meaning |
|---|---|
| static method | Belongs to class, not object |
| Access using | ClassName::method() |
No $this |
✔ Cannot use $this inside static |
| Good for | Utility methods, helpers, math functions |
| Works with inheritance | ✔ Yes |
