PHP Static Methods & Properties
In this page:
What are Static Members?
A static method or property, declared with the static keyword, belongs to the class itself rather than to any individual object, meaning it's shared across every instance and can even be called with no instance at all.
Example: What are Static Members?
<?php
class MathHelper {
static function square($n) {
return $n * $n;
}
}
echo MathHelper::square(4);
?>
Login to try C/C++/Java/PHP code in the editor
Static Methods
You call a static method using the class name and :: (scope resolution operator), like MathHelper::square(4), rather than through an object with ->.
Example: Static Methods
<?php
class MathHelper {
static function square($n) {
return $n * $n;
}
}
echo MathHelper::square(5);
?>
Login to try C/C++/Java/PHP code in the editor
Static Properties
Static properties retain their value between calls and are shared by all instances of the class, which makes them useful for things like a counter that tracks how many objects of a class have been created so far.
Example: Static Properties
<?php
class Counter {
static $count = 0;
function __construct() {
self::$count++;
}
}
new Counter();
new Counter();
echo Counter::$count;
?>
Login to try C/C++/Java/PHP code in the editor
Static parent Calls
Static methods cannot access $this, since there's no specific object instance they're running on — they can only work with static properties or with parameters passed in explicitly.
Example: Static parent Calls
<?php
class Formatter {
static $prefix = "LOG: ";
static function format($msg) {
return self::$prefix . $msg;
}
}
echo Formatter::format("Started");
?>
Login to try C/C++/Java/PHP code in the editor
When to Use Static
Static members are a good fit for utility functions that don't depend on any particular object's state, like a formatting helper, but overusing static state for things that should vary per-object can make code harder to test.
Example: When to Use Static
<?php
class StringHelper {
static function slugify($text) {
return strtolower(str_replace(" ", "-", $text));
}
}
echo StringHelper::slugify("Hello World");
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: