PHP - Static Properties
Sure! In PHP, static properties belong to a class rather than to any individual instance of the class. This means that static properties are shared across all instances of the class. They can be accessed without needing to create an instance of the class.
Key Points about Static Properties:
- Shared Across Instances: All instances of a class share the same static properties.
- Accessed via Class Name: Static properties are accessed using the class name, not through instances of the class.
- Defined with
static
Keyword: Static properties are declared using thestatic
keyword. - No
self
Keyword: Inside a class method, you should useself::$property
to refer to static properties.
Example
Here's a simple example to illustrate how static properties work:
<?php
class MyClass {
// Define a static property
public static $count = 0;
// Static method to increment the static property
public static function incrementCount() {
self::$count++;
}
// Static method to get the value of the static property
public static function getCount() {
return self::$count;
}
}
// Access static property and methods without creating an instance
echo "Initial count: " . MyClass::getCount() . "<br>";
MyClass::incrementCount();
MyClass::incrementCount();
echo "Count after incrementing twice: " . MyClass::getCount() . "<br>";
// Create instances of the class
$instance1 = new MyClass();
$instance2 = new MyClass();
// Access static property via instances (not recommended but possible)
echo "Count from instance 1: " . $instance1::getCount() . "<br>";
echo "Count from instance 2: " . $instance2::getCount() . "<br>";
?>
Output
Initial count: 0
Count after incrementing twice: 2
Count from instance 1: 2
Count from instance 2: 2
Explanation
- Static Property Initialization:
public static $count = 0;
declares a static property$count
that starts at 0. - Static Methods:
incrementCount()
andgetCount()
are static methods that modify and access the static property$count
. - Access Without Instance:
MyClass::getCount()
andMyClass::incrementCount()
show how to use static methods and properties without creating an instance. - Shared Across Instances: The count remains the same regardless of whether accessed through
MyClass
or instances like$instance1
and$instance2
.
This demonstrates how static properties can be used to maintain state that is common across all instances of a class.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.