PHP Static Members
Static members belong to a class itself rather than to one object. They are reached through the class name with a double colon.
A static method called on the class
This call names the class before the method.
<?php
class Dog {
public static function sound() {
return "Woof";
}
}
echo Dog::sound(), "\n";A class constant read from the class
The constant is read from the class itself.
<?php
class Dog {
const SOUND = "Woof";
}
echo Dog::SOUND, "\n";self:: inside the class
The static method builds its line from the class constant.
<?php
class Dog {
const SOUND = "Woof";
public static function soundLine() {
return "The dog says " . self::SOUND;
}
}
echo Dog::soundLine(), "\n";Example
<?php
class Converter {
const UNIT = "cm";
public static function toCm($meters) {
return $meters * 100;
}
}
echo Converter::toCm(2), " ", Converter::UNIT, "\n";Key points
- A static member belongs to the class, not to one object.
- No object is needed to use a static member.
- Static members are reached with the class name followed by two colons.
- A class constant is a value stored on the class itself.
- Inside the class, self:: names the class itself.
In this example, Converter holds a constant named UNIT. Its static method multiplies meters by 100. Both members are used through the Converter name. No Converter object is made.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz PHP Compiler
Exercise
How is the static method sound() on the class Dog called?