I have found different information regarding static variables in PHP but nothing that actually explains what it is and how it really works.
I have read that when used within a class that a static property cannot be used by any object instantiated by that class and that a static method can be used by an object instantiated by the class?
However, I have been trying to research what a static variable does within a function that is not in a class. Also, does a static variable within a function work somewhat like closure in javascript or am I totally off in this assumption?
It depends on what you mean by that. eg:
Yes, an instantiated object belonging to the class can access a static method.
The keyword
static
in the context of classes behave somewhat like static class variables in other languages. A member (method or variable) declaredstatic
is associated with the class and rather than an instance of that class. Thus, you can access it without an instance of the class (eg: in the example above, I could useFoo::$my_var
)Outside of classes (ie: in functions), a
static
variable is a variable that doesn't lose its value when the function exits. So in sense, yes, they work like closures in JavaScript.But unlike JS closures, there's only one value for the variable that's maintained across different invocations of the same function. From the PHP manual's example:
Reference:
static
keyword (in classes), (in functions)First: for the add_student function, the best practice is to use static not public. Second: in the add_student function, we are using Student::$total_student,not use $this->total_student. This is big different from normal variable. Third:static variable are shared throughout the inheritance tree.
take below code to see what is the result:
A static variable in a function is initialized only in the first call of that function in its running script.
At first i will explain what will happen if static variable is not used
If you run the above code the output you gets will be 1 1 1 . Since everytime you called that function variable assigns to 1 and then prints it.
Now lets see what if static variable is used
Now if you run this code snippet the output will be 1 2 3.
Note: Static keeps its value and stick around everytime the function is called. It will not lose its value when the function is called.
static
has two uses in PHP:First, and most commonly, it can be used to define 'class' variables/functions (as opposed to instance variables/functions), that can be accessed without instantiating a class:
Secondly, it can be used to maintain state between function calls:
Note that declaring a variable static within a function works the same regardless of whether or not the function is defined in a class, all that matters is where the variable is declared (class member or in a function).