Adrik
Adrik

Reputation: 23

Set function's static variable outside function

If we have

function counter() {
    static $count = 0;

    $count++;

    return $count;
}

can we set value of $count outside of function counter()?

I know that you can get values of all static variables inside of function with Reflection:

$vars = (new ReflectionFunction('counter'))->getStaticVariables()

but I can't find simmilar thing for setting.

Upvotes: 1

Views: 97

Answers (2)

Don't Panic
Don't Panic

Reputation: 41810

You can add an optional parameter and override the static initialization if it is provided.

function counter($init = null) {
    static $count = 0;

    if (!is_null($init)) $count = $init;

    $count++;

    return $count;
}

Upvotes: 0

Simon R
Simon R

Reputation: 3772

Wouldn't it be easier to just do the following;

$count = 1;

function counter() {
    global $count;

    $count++;

    return $count;
}

die(var_dump(counter()));

This way because $count is globally available you can set the value of it to whatever it needs to be on initialisation.

Upvotes: 2

Related Questions