Nadine
Nadine

Reputation: 787

Why doesn't this work? static $myvar = $my_array[3];

static $myvar = $my_array[3];

I've never needed to use the static function until now. But I need to use it to either store the return value from a function or an array:

static $myvar = $my_array[3];

static $myvar = my_func();

Why can't I use it like this? Is static only used for intergers?

Upvotes: 0

Views: 123

Answers (4)

Drahcir
Drahcir

Reputation: 11972

From the page at Static Variables:

Static declarations are resolved in compile-time.

See example 7 on the linked page.

This is why you can't assign $my_array[3] to a static variable. The contents of the variable is not known at compile time.

Upvotes: 0

hek2mgl
hek2mgl

Reputation: 158050

I'm not sure if you are searching for this:

function foo() {
    static $counter;
    if(!$counter) {
        $counter = 0;
    }

    $counter++;
    echo $counter;
}

Note that beside the usage in OOP programming, the static keyword can be used to declare static variables in a function body that should be initialized only once.

So calls to foo() will give you the following output, as $counter is initialized only the first time foo() is called:

foo(); // 1
foo(); // 2

Upvotes: 2

EnigmaRM
EnigmaRM

Reputation: 7632

Looks like you aren't using it correctly. Refer to PHP.net: Static Keyword. You need to be using it inside of a class. And I'm not sure if you need to specify public private protected.

Upvotes: 0

Eddie Jaoude
Eddie Jaoude

Reputation: 1708

Take a look at PHP Static

Static is for OOP

Upvotes: 0

Related Questions