Poe
Poe

Reputation: 3010

Using static vars in PHP functions

The use of the static $var in this function works, but I'm wondering if there's a more efficient way to handle a situation like this.

function static_test() {
    static $var = FALSE;
    if ( ! $var) $var = date('Ymd');
    // do some stuff with $var
}

I wondered if possible to do something closer to this... or other to declare the static $var.

function static_test() {
    static $var = date('Ymd');
    // do some stuff with $var
}

How would you do it?

Upvotes: 0

Views: 228

Answers (2)

Alfredo Castaneda Garcia
Alfredo Castaneda Garcia

Reputation: 1659

The second option is almost fine. As you may read here: http://www.php.net/manual/en/language.variables.scope.php,

...[a static variable] is initialized only in first call of function...

So there is no need for this piece of code: if ( ! $var) $var = date('Ymd');

However, you need a dummy:

$dummy=date('Ymd'); static $var=$dummy;

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191819

The second example is simply not in php syntax. I loathe static var usage at all, but especially in this instance. I would use a class.

Upvotes: 0

Related Questions