Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Check if static variable has been declared or initialized?

Tags:

php

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?

like image 879
user139301 Avatar asked Dec 03 '25 22:12

user139301


1 Answers

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...

like image 57
nice ass Avatar answered Dec 06 '25 12:12

nice ass