Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the second static variable assignment takes effect not the first one?

function track_times() {
static $i = 0;
$i++;
static $i = 5;
return $i;
}

echo track_times() . "\n";
echo track_times() . "\n";

The result is:

6
7

I know people don't use static variables in this way, just can't explain the result. The result implies the second assignment takes effect, but $i increments itself before the assignment, so why the first invocation of the function returns 6?

like image 732
samluthebrave Avatar asked Jul 05 '13 02:07

samluthebrave


People also ask

Why static variable initialized only once?

When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name. Static variables are initialized only once.

What is the order of static variable initialization across one program?

Within a single compilation unit, static variables are initialized in the same order as they are defined in the source (this is called Ordered Dynamic Initialization). Across compilation units, however, the order is undefined: you don't know if a static variable defined in a.

What is the effectiveness of the static member variable?

Throughout the program, only one copy of the static member variable is created for the entire class hence static member variables are also called class variables. It is shared by all instances of the class. The static member variable is only visible within the class but its lifetime is till the program ends.

Can we declare static variables multiple times?

A static variable declaration is only executed once, the first time the function is executed.


1 Answers

Static declarations are resolved in compile-time. You are incrementing it during runtime. Therefore you are incrementing it after it's already declared as 5. See also http://www.php.net/manual/en/language.variables.scope.php

like image 145
Rob Avatar answered Nov 01 '22 00:11

Rob