In PHP OOP, static properties are properties that belong to a class, rather than an instance of a class. Static properties can be accessed and modified without creating an object of the class.
Here’s an example of a class with a static property:
class Counter {
public static $count = 0;
public function increment() {
self::$count++;
}
}
echo Counter::$count; // Output: 0
$counter1 = new Counter();
$counter1->increment();
echo Counter::$count; // Output: 1
$counter2 = new Counter();
$counter2->increment();
echo Counter::$count; // Output: 2
In this example, the Counter
class has a static property named $count
, which is initially set to 0. The class also has a method named increment()
, which increments the $count
property by 1. We can access the $count
property on the Counter
class without creating an object of the class.
echo Counter::$count; // Output: 0
We can also create objects of the Counter
class and call the increment()
method on those objects, which will modify the $count
property.
$counter1 = new Counter();
$counter1->increment();
echo Counter::$count; // Output: 1
$counter2 = new Counter();
$counter2->increment();
echo Counter::$count; // Output: 2
In this example, both $counter1
and $counter2
are separate instances of the Counter
class, but they both modify the same static property, $count
.
Static properties can also be used to keep track of global state in a program, or to share data between instances of a class.
In summary, static properties in PHP OOP are properties that belong to a class, rather than an instance of a class. Static properties can be accessed and modified without creating an object of the class. Static properties can be used to keep track of global state in a program, or to share data between instances of a class.