PHP OOP - Static Properties

In PHP, a static property is a class property that belongs to the class itself rather than to individual instances (objects) of the class. This means that all instances of the class share the same static property value. Static properties are declared using the `static` keyword in the property declaration.


Here's how you define and use a static property in PHP:

php
class MyClass {
    public static $staticProperty = 0;
}

To access a static property, you don't need to create an object; you can directly access it using the class name followed by `::` and the property name:


php
echo MyClass::$staticProperty;


Since static properties are associated with the class itself, they are commonly used for class-level configuration, global counters, or other data that should be shared across all instances of the class.


Here's an example illustrating the use of static properties:

php
class Counter {
    public static $count = 0;

    public function increment() {
        self::$count++;
    }

    public function getCount() {
        return self::$count;
    }
}

$counter1 = new Counter();
$counter2 = new Counter();

$counter1->increment();
$counter2->increment();

echo $counter1->getCount(); // Output: 2
echo $counter2->getCount(); // Output: 2

In this example, the `Counter` class has a static property `$count`, which is used to keep track of the number of instances created. The `increment()` method increases the count, and the `getCount()` method returns the current count. Both instances of the `Counter` class share the same `$count` property because it is a static property.


It's essential to note that static properties are not bound to specific instances, and their values persist across different objects of the same class. Therefore, modifying a static property from one instance will affect all other instances of the class as well. This behavior should be used with caution, and static properties are typically used for shared state or global configuration settings.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext