3

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?

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

The point is to know if the function has been run before or if it is the first time. I want the function to behave differently if it is being used in a loop. I did not think about separating variable assignment during declaration.
@user Sounds like a bad idea. Functions should not behave differently in a loop or elsewhere. Research "idempotence".
2

you can do

function init_i (){
    static $i=0;

    // check if $i is set??
    if ( $i != 0 )
         echo '$i is static and is set ';
    $i++;
    echo "$i<br>";
}

1 Comment

oops you're right. i had 2 echo 'i is static and is set' lines in there giving me false results. i will remove that 2nd function from my answer
0

check the condition after declared the static variable

static $i=0;
if(isset($i)){
 echo '$i is static and is set ';
}else{
$i=0;
}

2 Comments

But then the first time function is run, the if statement will prove true. I would like it to prove true the second time and beyond.
yeah check it in else condition as well

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.