What is it?
A static property or method belongs to the CLASS itself, not to any specific object instance. You call them with :: and do not need to create an object first.
Why does it matter?
Static members are ideal for utilities (helper functions), shared counters, factory methods, and the Singleton pattern. They are a common topic in PHP developer interviews.
Learn static methods, static properties, utility classes, and the Singleton pattern.
Real-World Use Cases
- 🛠️ Helper/Utility classes - StringHelper::slugify(), NumberHelper::formatCurrency(), DateHelper::toIST() — static utility methods with no state.
- 🔢 Request counter - A static $requestCount property tracks how many times an API has been called across all instances in the same request.
- 🏭 Factory methods - User::create($email, $password) as a static method creates and returns a new User object — a cleaner alternative to new User().
- 🔌 Database singleton - Database::getInstance() returns the same PDO connection across the entire application — one connection, no duplication.
Static Properties and Methods
Static members belong to the class itself, not an object.
class Counter
{
public static int $count = 0;
public static function increment()
{
self::$count++;
}
}
Counter::increment();
Counter::increment();
echo Counter::$count; // 2
Use Cases
- Counters
- Configuration values
- Utility functions
- Shared data
Static Utility Class
A class containing only static methods.
class StringHelper
{
public static function slug(string $text): string
{
return strtolower(str_replace(' ', '-', $text));
}
public static function upper(string $text): string
{
return strtoupper($text);
}
}
echo StringHelper::slug("Hello World");
// hello-world
Benefits
- No object creation needed
- Easy reusable helper functions
Singleton Pattern
Ensures only one instance of a class exists.
class Database
{
private static ?Database $instance = null;
private function __construct()
{
echo "Connected";
}
public static function getInstance(): Database
{
if (self::$instance === null) {
self::$instance = new Database();
}
return self::$instance;
}
}
$db1 = Database::getInstance();
$db2 = Database::getInstance();
var_dump($db1 === $db2); // true
Comparison
| Feature | Static Class | Singleton |
|---|---|---|
| Object Created | ❌ No | ✅ One |
| Stores State | Limited | Yes |
| Access | Class::method() | getInstance()->method() |
| Use Case | Helpers, Utilities | Database, Logger, Config |
Q: What is the difference between self:: and static::?
self:: always refers to the class where the method is defined. static:: uses late static binding and refers to the class that was actually called. In inheritance, static:: refers to the child class while self:: still refers to the parent.
Comments (0)
No comments yet. Be the first!
Leave a Comment