I want to check if a static variable has been declared/initialized previously, e.g. if a function with a static variable is being run for the first time. See the following example code:
function init_i (){
// check if $i is set??
if(isset($i)) echo '$i is static and is set ';
static $i=0;
$i++;
echo "$i<br>";
}
function run_init(){
init_i();
}
run_init(); //output 1
run_init(); //should output $i is static and is set 2
run_init(); //should output $i is static and is set 3
run_init(); //should output $i is static and is set 4
run_init(); //should output $i is static and is set 5
The problem is that isset($i) never seems to prove true even though it is a static variable. How do I check static $i has already been set?
Just omit out the default value, and it will be null:
static $i;
// check if $i is set??
if(isset($i)){
echo '$i is static and is set ';
}else{
// first call, initialize...
$i = 0;
}
...
isset() returns TRUE if variable is set and not null.
I don't get what's your reasoning behind this, because you can just check the value is the initial value (0) and you know that's the first call...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With