9

I have a construction like this in my config file:

<?php
if (true) {
    $nonstatic = 1;
    static $config = 1;
}
else {
    $nonstatic = 2;
    static $config = 2;
}

echo $nonstatic;
echo $config;
?>

So why the $config contains 2 if this part of the statement is false and $nonstatic contains 1? Is it a bug?

9
  • Is this the entire script, or is there more code? Commented Sep 13, 2011 at 16:16
  • 1
    Wouldn't you be better declaring the variable outside the if and simply assigning it a value inside? I've never seen the static keyword used like this, although that doesn't mean it's wrong...
    – DaveRandom
    Commented Sep 13, 2011 at 16:16
  • Seems like last static declaration (irrespective of anything) decides the value.
    – Vikash
    Commented Sep 13, 2011 at 16:18
  • @Michael, of course there is more code. This is a simplified version, describing what I am trying to reach.
    – Aldekein
    Commented Sep 13, 2011 at 16:19
  • @DaveRandom since it's a configuration file for a project I would like for the variable to be read-only.
    – Aldekein
    Commented Sep 13, 2011 at 16:20

1 Answer 1

11

I suppose this chunk is being included from a function.

Initialisations of static variables are resolved at compile-time, and if the interpreter finds multiple initialisations, it simply takes the bottom one.

1
  • In particular, this means that conditionals around a static initialisation have no effect. Commented Sep 13, 2011 at 16:24

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.