$count = 5; function get_count() { static $count = 0; return $count++; } echo $count; ++$count; echo get_count(); echo get_count();
I guessed it outputs 5 0 1 and it's right,but I need a better explanation?
Introduction: A static class in PHP is a type of class which is instantiated only once in a program. It must contain a static member (variable) or a static member function (method) or both. The variables and methods are accessed without the creation of an object, using the scope resolution operator(::).
Global is used to get the global vars which may be defined in other scripts, or not in the same scope. e.g. Static is used to define an var which has whole script life, and init only once.
No. Static can be used to declare class variables or within function to declare a variable which persists over function calls, but not over executions of the script.
Static properties are accessed using the Scope Resolution Operator ( :: ) and cannot be accessed through the object operator ( -> ). It's possible to reference the class using a variable. The variable's value cannot be a keyword (e.g. self , parent and static ). print $foo::$my_static .
The variable $count
in the function is not related in any kind to the global $count
variable. The static
keyword is the same as in C or Java, it means: Initialize this variable only once and keep its state when the function ends. This means, when execution re-enters the function, it sees that the inner $count has already been initialized and stored the last time as 1
, and uses that value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With