Static variables in PHP

I have read that when used within a class that a static property cannot be used by any object instantiated by that class

It depends on what you mean by that. eg:

class Foo {
    static $my_var="Foo";

$x = new Foo();

echo $x::$my_var;  // works fine
echo $x->my_var;   // doesn't work - Notice: Undefined property: Foo::$my_var

and that a static method can be used by an object instantiated by the class???

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) declared static 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 use Foo::$my_var)

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.

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:

function test()
    static $a = 0;
    echo $a;

test();  // prints 0
test();  // prints 1
test();  // prints 2

Reference: static keyword (in classes), (in functions)

Leave a Comment