Home > Article > Backend Development > php--static keyword
This page explains the use of static keyword to define static methods and properties. static can also be used to define static variables and late static binding.
Declaring a class attribute or method as static allows you to access it directly without instantiating the class. Static properties cannot be accessed through an object of a class that has been instantiated (but static methods can).
In order to be compatible with PHP 4, if no access control is specified, properties and methods default to public.
Since static methods do not need to be called through objects, the pseudo variable $this is not available in static methods.
Static properties cannot be accessed by objects through the -> operator.
Calling a non-static method statically will result in an E_STRICT level error.
Like all other PHP static variables, static properties can only be initialized to literals or constants, not expressions. So a static property can be initialized to an integer or an array, but it cannot be initialized to another variable or function return value, nor can it point to an object.
Example #1 Static property example
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.'<br>'; $foo = new Foo(); print $foo->staticValue().'<br>'; print $foo->my_static.'<br>'; print $foo::$my_static.'<br>'; $classname = 'Foo'; print $classname::$my_static; print Bar::$my_static.'<br>'; $bar = new Bar(); print $bar->fooStatic().'<br>';