Static properties are class variables shared across all instances of a class. Unlike instance properties, static properties belong to the class definition itself and retain their value state across all object instances.
self::$propertyName or static::$propertyNameClassName::$propertyNameflowchart TD
A["Static Property (User::$instanceCount)"] --> B["Object Instance 1"]
A --> C["Object Instance 2"]
A --> D["Object Instance 3"]
B & C & D -->|All instances read & update SAME memory state| A
<?php
declare(strict_types=1);
class DatabaseConnectionPool
{
// Shared Static Property tracking total active instances
public static int $activeConnections = 0;
public function __construct(public string $connectionName)
{
// Increment shared class counter
self::$activeConnections++;
}
public function close(): void
{
if (self::$activeConnections > 0) {
self::$activeConnections--;
}
}
public function __destruct()
{
// Decrement on garbage collection
}
}
$conn1 = new DatabaseConnectionPool("Main_DB");
$conn2 = new DatabaseConnectionPool("Analytics_DB");
$conn3 = new DatabaseConnectionPool("Cache_DB");
echo "Active Connections Count: " . DatabaseConnectionPool::$activeConnections . "
"; // Outputs 3
$conn1->close();
echo "Active Connections After 1 Close: " . DatabaseConnectionPool::$activeConnections . "
"; // Outputs 2
$ Sign When Accessing Static Properties: Write ClassName::$prop (with $), unlike static methods or constants.Write a static property declaration public static int $counter = 0; inside a class VisitorCounter and increment it inside __construct()!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.