Static Members in Depth
Static members in depth covers values and methods that live on the class itself. One shared value on the class serves every object made from it.
A static property counts the objects
The Counter constructor adds one to the static count on each new object. The static read method prints 1, then 2, then 3 after the three new calls.
<?php
class Counter {
public static $count = 0;
public function __construct() {
self::$count = self::$count + 1;
}
public static function read() {
echo self::$count, "\n";
}
}
$first = new Counter();
Counter::read();
$second = new Counter();
Counter::read();
$third = new Counter();
Counter::read();self:: reads the parent and static:: reads the child
Both methods live in Animal, and Dog replaces the KIND constant. The self:: line prints the Animal value, while the static:: line prints the Dog value.
<?php
class Animal {
const KIND = "Animal";
public static function kindViaSelf() {
echo self::KIND, "\n";
}
public static function kindViaStatic() {
echo static::KIND, "\n";
}
}
class Dog extends Animal {
const KIND = "Dog";
}
Dog::kindViaSelf();
Dog::kindViaStatic();A static call beside an object call
The sound method is static, so the call names the class and needs no object. The speak method reads the name of one object, so it runs on the dog object.
<?php
class Dog {
public $name = "";
public static function sound() {
echo "Woof\n";
}
public function speak() {
echo $this->name . " says hello\n";
}
}
Dog::sound();
$dog = new Dog();
$dog->name = "Rex";
$dog->speak();Example
<?php
class Member {
public static $total = 0;
const ROLE = "Member";
public function __construct() {
self::$total = self::$total + 1;
}
public static function role() {
echo static::ROLE, "\n";
}
public static function total() {
echo self::$total, "\n";
}
}
class Admin extends Member {
const ROLE = "Admin";
}
$first = new Member();
$second = new Member();
$admin = new Admin();
Member::total();
Admin::role();
Member::role();Key points
- A static property holds one value for the whole class.
- Every object of the class shares that one static value.
- self:: names the class where the code is written.
- static:: names the class used in the call.
- A child can replace a class constant, and static:: then reads the child value.
- A static method runs without an object, so it cannot use $this.
In this example, three objects are made, and the shared static total rises to 3. The role method reads its constant with static::, so the Admin call prints Admin. The Member call prints Member from the parent constant.
Note
Late static binding is the name for the late choice that static:: makes.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A parent method prints static::KIND, and the call is made through a child that replaces the KIND constant. Which value prints?