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?

Benjamin Crouzier
  • 40,265
  • 44
  • 171
  • 236
Aldekein
  • 3,538
  • 2
  • 29
  • 33
  • Is this the entire script, or is there more code? – Michael Berkowski Sep 13 '11 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 Sep 13 '11 at 16:16
  • Seems like last static declaration (irrespective of anything) decides the value. – Vikash Sep 13 '11 at 16:18
  • @Michael, of course there is more code. This is a simplified version, describing what I am trying to reach. – Aldekein Sep 13 '11 at 16:19
  • @DaveRandom since it's a configuration file for a project I would like for the variable to be read-only. – Aldekein Sep 13 '11 at 16:20
  • @Aldekein In that case, should consider using a constant instead... – DaveRandom Sep 13 '11 at 16:21
  • The static keyword is not really meant to be used outside a class. What i think happens is that the second "static" statement overrides the first at compile-time. As it is normally used in class declarations it is not built to support this kind of usage. What is it you are trying to accomplish? – Johan Sep 13 '11 at 16:22
  • @Johan: static keyword can [definitely be used outside of classes](http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static) in PHP, by design. However, OP was incorrectly trying to use them as constants. – webbiedave Sep 13 '11 at 16:45
  • @webbiedave Ah tnx! Thought it was bad practice. I was right about the compile-time/scope thing though :) – Johan Sep 14 '11 at 08:46

1 Answers1

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
MauganRa
  • 494
  • 6
  • 8