Static Members, Constants and Traits
static properties and methods belong to the class and are used with ::. Class constants use const. A trait lets you reuse methods in several unrelated classes. Enums (PHP 8.1) define fixed sets of values.
Example
class Counter {
public static int $total = 0;
const PREFIX = "No.";
public static function next(): string { return self::PREFIX . ++self::$total; }
}
echo Counter::next(), " ", Counter::next(), "\n";
trait Greets {
public function hello() { return "Hello from " . static::class; }
}
class Robot { use Greets; }
echo (new Robot)->hello(), "\n";
enum Level: string {
case Beginner = "beginner";
case Advanced = "advanced";
}
echo Level::Advanced->value, "\n";Result
No.1 No.2 Hello from Robot advanced
Exercise
Reach a static member.
echo Counter$total;
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.