This page describes the use of the static keyword to
define static methods and properties. static can also
be used to
define static variables
and for
late static bindings.
Please refer to those pages for information on those meanings of
static.
Declaring class properties or methods as static makes them accessible without needing an instantiation of the class. A property declared as static cannot be accessed with an instantiated class object (though a static method can).
Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.
Calling non-static methods statically throws an Error.
Prior to PHP 8.0.0, calling non-static methods statically is deprecated, and will
generate an E_DEPRECATED warning.
Example #1 Static method example
<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod();
?>
Static properties cannot be accessed through the object using the arrow operator ->.
Like any other PHP static variable, static properties may be
initialized with the same rules apply as const
expressions: some limited expressions are possible, provided they can be
evaluated at compile time.
It's possible to reference the class using a variable.
The variable's value cannot be a keyword (e.g. self,
parent and static).
Example #2 Static property example
<?php
class Foo
{
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static;
}
}
class Bar extends Foo
{
public function fooStatic() {
return parent::$my_static;
}
}
print Foo::$my_static . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n"; // Undefined "Property" my_static
print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n";
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>