PHP OOP Static Methods

PHP Tutorial

 PHP OOP Static Methods

In PHP OOP Static Methods belongs to the class, NOT the object.
  •  You can call it without creating an object
  •  Use the keyword static 
  •  Access using ClassName::methodName()

  Basic Static Method Example


 

Test::hello(); // No need to create object


  Static Method Inside Class

You can still call static methods from inside the class using self::.


 


  Static Method with Parameters


 


  Static Method vs Object Method

TypeCalled ByUse
Static MethodClassName::method()Utility functions, helpers
Object Method$object->method()When data belongs to object

Static Methods Cannot Use $this

 This will cause an error:


Because $this refers to an object, and static methods are not part of any object.


  Calling Static Methods from Child Classes (Inheritance)


 


  Overriding Static Methods in Child Class


 


 Late Static Binding (Important)

Use static:: when you want the child class’s static method/property.


 


  Real-Life Example – Helper Class


 


 Real-Life Example – DB Connection (Singleton Pattern)


 Summary (Easy to Remember)

FeatureMeaning
static methodBelongs to class, not object
Access usingClassName::method()
No $this Cannot use $this inside static
Good forUtility methods, helpers, math functions
Works with inheritance Yes

You may also like...