PHP Static Properties
Sharing data across all class instances
📊 What are Static Properties?
Static properties belong to the class itself, not to individual objects. They are shared across all instances of the class, making them perfect for storing data that should be common to all objects.
<?php
// Simple static property example
class User {
public static $count = 0;
public function __construct() {
self::$count++;
}
}
new User();
new User();
echo User::$count; // 2
?>
Why Use Static Properties?
Shared Data
One value shared by all instances
Counters
Track instances or operations
Configuration
Store class-level settings
Memory Efficient
One copy for all objects
🔹 Basic Static Property
Static properties are declared with the static keyword and accessed using the double colon operator. They maintain their value across all instances of the class.
<?php
class Database {
public static $connection = "Not connected";
public static $queries = 0;
public static function connect() {
self::$connection = "Connected";
}
public static function query() {
self::$queries++;
return "Query executed";
}
}
Database::connect();
Database::query();
Database::query();
echo "Status: " . Database::$connection . "<br>";
echo "Total queries: " . Database::$queries;
?>
Output:
Status: Connected
Total queries: 2
🔹 Instance Counter Example
A common use of static properties is counting how many instances of a class have been created, useful for tracking object creation and resource management.
<?php
class Product {
public static $totalProducts = 0;
public $name;
public function __construct($name) {
$this->name = $name;
self::$totalProducts++;
}
public static function getTotal() {
return self::$totalProducts;
}
}
$product1 = new Product("Laptop");
$product2 = new Product("Phone");
$product3 = new Product("Tablet");
echo "Product 1: " . $product1->name . "<br>";
echo "Product 2: " . $product2->name . "<br>";
echo "Total products created: " . Product::getTotal();
?>
Output:
Product 1: Laptop
Product 2: Phone
Total products created: 3
🔹 Accessing Static Properties
Static properties can be accessed from inside the class using self::, static::, or parent::, and from outside using the class name with the scope resolution operator.
<?php
class Config {
public static $appName = "MyApp";
public static $version = "1.0";
private static $apiKey = "secret123";
public static function getInfo() {
return self::$appName . " v" . self::$version;
}
public static function getApiKey() {
return self::$apiKey;
}
}
// Access from outside
echo "App: " . Config::$appName . "<br>";
echo "Version: " . Config::$version . "<br>";
// Access through method
echo Config::getInfo() . "<br>";
echo "API Key: " . Config::getApiKey();
?>
Output:
App: MyApp
Version: 1.0
MyApp v1.0
API Key: secret123
🔹 Static vs Instance Properties
Understanding the difference between static and instance properties is crucial. Static properties are shared, while instance properties are unique to each object.
<?php
class BankAccount {
public static $bankName = "MyBank";
public static $totalAccounts = 0;
public $accountNumber;
public $balance;
public function __construct($accountNumber, $balance) {
$this->accountNumber = $accountNumber;
$this->balance = $balance;
self::$totalAccounts++;
}
public function getInfo() {
return "Bank: " . self::$bankName .
", Account: " . $this->accountNumber .
", Balance: $" . $this->balance;
}
}
$account1 = new BankAccount("001", 1000);
$account2 = new BankAccount("002", 2000);
echo $account1->getInfo() . "<br>";
echo $account2->getInfo() . "<br>";
echo "Total accounts: " . BankAccount::$totalAccounts;
?>
Output:
Bank: MyBank, Account: 001, Balance: $1000
Bank: MyBank, Account: 002, Balance: $2000
Total accounts: 2
🔹 Modifying Static Properties
Static properties can be modified from anywhere in your code, and the changes will be reflected across all instances and future accesses.
<?php
class Settings {
public static $theme = "light";
public static $language = "en";
public static function changeTheme($newTheme) {
self::$theme = $newTheme;
}
public static function getSettings() {
return "Theme: " . self::$theme . ", Language: " . self::$language;
}
}
echo Settings::getSettings() . "<br>";
// Change static property
Settings::$language = "es";
Settings::changeTheme("dark");
echo Settings::getSettings();
?>
Output:
Theme: light, Language: en
Theme: dark, Language: es
🔹 Static Properties in Inheritance
Child classes inherit static properties from parent classes. Changes to static properties in child classes affect only that child class, not the parent.
<?php
class Vehicle {
public static $wheels = 4;
public static function getWheels() {
return static::$wheels;
}
}
class Motorcycle extends Vehicle {
public static $wheels = 2;
}
class Car extends Vehicle {
public static $wheels = 4;
}
echo "Vehicle wheels: " . Vehicle::$wheels . "<br>";
echo "Motorcycle wheels: " . Motorcycle::getWheels() . "<br>";
echo "Car wheels: " . Car::getWheels();
?>
Output:
Vehicle wheels: 4
Motorcycle wheels: 2
Car wheels: 4
🔹 Practical Example: Session Manager
Static properties are excellent for managing application-wide state like sessions, configurations, or singleton patterns that need to be accessed globally.
<?php
class Session {
private static $data = [];
private static $started = false;
public static function start() {
if (!self::$started) {
self::$started = true;
return "Session started";
}
return "Session already active";
}
public static function set($key, $value) {
self::$data[$key] = $value;
}
public static function get($key) {
return self::$data[$key] ?? "Not found";
}
public static function getAll() {
return self::$data;
}
}
echo Session::start() . "<br>";
Session::set("user", "John");
Session::set("role", "admin");
echo "User: " . Session::get("user") . "<br>";
echo "Role: " . Session::get("role") . "<br>";
echo "Email: " . Session::get("email");
?>
Output:
Session started
User: John
Role: admin
Email: Not found
🔹 Static Property Visibility
Like regular properties, static properties can be public, protected, or private, controlling where they can be accessed from in your code.
<?php
class Security {
public static $publicKey = "public123";
protected static $protectedKey = "protected456";
private static $privateKey = "private789";
public static function getKeys() {
return [
"public" => self::$publicKey,
"protected" => self::$protectedKey,
"private" => self::$privateKey
];
}
}
// Access public property
echo "Public: " . Security::$publicKey . "<br>";
// Access all through method
$keys = Security::getKeys();
echo "Protected: " . $keys['protected'] . "<br>";
echo "Private: " . $keys['private'];
?>
Output:
Public: public123
Protected: protected456
Private: private789
💡 Key Points to Remember:
- Static properties belong to the class, not instances
-
Declared with the
statickeyword -
Accessed using
::operator -
Use
self::$propertyinside the class -
Use
ClassName::$propertyoutside the class - Shared across all instances of the class
- Can have visibility modifiers (public, protected, private)
- Perfect for counters, configuration, and shared state