static is a built-in keyword in php. We can use the static keyword to define static methods and properties, and can also be used to define static variables and late static binding.
The operating environment of this article: windows7 system, PHP7.4 version, DELL G3 computer
What does php static mean?
static is a built-in keyword in PHP.
Static keyword
Tips
This page explains the use of the static keyword to define static methods and properties. static can also be used to define static variables and late static binding. See the above page to see how static is used there.
Declaring class attributes or methods as static allows direct access without instantiating the class. Can be accessed statically within an instantiated class object.
Static method
Since static methods do not need to be called through objects, the pseudo variable $this is not available in static methods.
Warning
Calling a non-static method statically will throw an Error.
Prior to PHP 8.0.0, statically calling a non-static method was deprecated and resulted in an E_DEPRECATED level warning.
Example #1 Static method example
<?php class Foo { public static function aStaticMethod() { // ... } } Foo::aStaticMethod(); $classname = 'Foo'; $classname::aStaticMethod(); ?>
Static properties
Static properties are accessed using the range resolution operator (::) and cannot be accessed through object operations character ( -> ) access.
It is possible to refer to a class through a variable, but the value of this variable cannot be a reserved word (such as self, parent and static)
Example #2 Static attribute 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"; // 未定义的 "属性" 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"; ?>
The output of the above routine in PHP 8 is similar to:
foo foo
Notice: Accessing static property Foo::$my_static as non static in /in/V0Rvv on line 23
Warning : Undefined property: Foo::$my_static in /in/V0Rvv on line 23
foo foo foo foo
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of php static what does it mean. For more information, please follow other related articles on the PHP Chinese website!