In PHP, static properties are properties that belong to the class itself rather than to instances (objects) of the class. They are shared among all instances of the class. Static properties are declared using the static keyword inside the class. These properties can be accessed without creating an instance of the class.
class ClassName {
public static $staticProperty;
}
Static properties are accessed using the ClassName::$propertyName syntax, where ClassName is the name of the class containing the static property.
class Math {
public static $pi = 3.14159;
}
// Accessing a static property
echo "The value of Pi is: " . Math::$pi; // Output: The value of Pi is: 3.14159
Static properties can be set and changed using the same syntax as accessing them.
class Counter {
public static $count = 0;
public static function increment() {
self::$count++;
}
}
Counter::$count = 5; // Set static property directly
echo "Count: " . Counter::$count . "<br>"; // Output: Count: 5
Counter::increment(); // Increment the count
echo "Count: " . Counter::$count . "<br>"; // Output: Count: 6
Since static properties are associated with the class itself, they are shared among all instances of the class. If you change the static property in one instance, it will affect all other instances as well.
class MyClass {
public static $sharedProperty = 0;
public function __construct() {
self::$sharedProperty++;
}
}
$obj1 = new MyClass();
$obj2 = new MyClass();
echo "Shared Property: " . MyClass::$sharedProperty; // Output: Shared Property: 2
Static Properties:
Non-Static Properties:
Static Properties Example:
Here's a more detailed example demonstrating the use of static properties:
class Product {
public $name;
public $price;
public static $count = 0;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
self::$count++; // Increment the count when a new instance is created
}
public static function getCount() {
return self::$count;
}
}
// Create some product objects
$product1 = new Product("Phone", 500);
$product2 = new Product("Laptop", 1200);
// Accessing static property
echo "Total products created: " . Product::getCount() . "<br>"; // Output: Total products created: 2
In this example:
Static properties in PHP allow you to define properties that belong to the class itself rather than to instances of the class. They are shared among all instances and can be accessed and modified without creating an instance of the class. Static properties are useful for keeping track of class-level data that should be common to all instances, such as counters, configuration settings, or utility data.