Reputation: 787
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
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
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
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