Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Static Local Variables

Tags:

php

static

So I recently ran across a code segment like this:

private static function FOO() {
        static $c = null;
        if ($c == null) {
            $c = new ParentClass_InnerClass();
        }
        return $c;
    }

So what is up with this code? How is this different from:

private static $C;

//other methods and fields    

private static function FOO() {
    if(!$self::c) {
        $self::c = new ParentClass_InnerClass();
    }
    return $self::c;
}

Or are they even the same concept?

like image 681
thatidiotguy Avatar asked Oct 24 '13 15:10

thatidiotguy


3 Answers

They are, essentially, the same concept, though the scope is different:

class Foobar
{
    private static $c = null;
    public static function FOO()
    {
        if (self::$c === null)
        {
            self::$c = new stdClass;
        }
        return self::$c;
    }
    public static function checkC()
    {
        if (self::$c === null)
        {
            return false;
        }
        return self::$c;
    }
}

Foobar::checkC();//returns false, as $c is null
//function checkC has access to $c
$returned = Foobar::FOO();//returns object
if ($returned === Foobar::checkC())
{//will be true, both reference the same variable
    echo 'The same';
}

Whereas, if we were to change the code to:

class Foobar
{
    public static function FOO()
    {
        static $c = null;
        if ($c === null)
        {
            $c = new stdClass;
        }
        return $c;
    }
    public static function checkC()
    {
        if ($c === null)
        {
            return false;
        }
        return $c;
    }
}

We will get a notice when calling checkC: undefined variable. the static variable $c is only accessible from within the FOO scope. A private property is scoped within the entire class. That's it really.
But really, do yourself a favour: only use statics if you need them (they're shared between instances, too). And in PHP, it's very rare you'll actually need a static.

like image 130
Elias Van Ootegem Avatar answered Sep 23 '22 21:09

Elias Van Ootegem


They're the same concept, except that in the first code block, the static variable is local to the function, and such a static variable could be used in any function, even outside the context of a class:

function test() {
    static $counter = 0;
    return $counter++;
}

echo test(); // 0
echo test(); // 1
like image 32
BenMorel Avatar answered Sep 23 '22 21:09

BenMorel


In the top example you can access $c only from the local scope (FOO()) and in the bottom example you can access $c from the entire class, so not only form FOO().

like image 37
Joren Avatar answered Sep 23 '22 21:09

Joren