40

The following PHP code will output 3.

function main() {
    if (1) {
        $i = 3;
    }
    echo $i;
}

main();

But the following C code will raise a compile error.

void main() {
    if (1) {
        int i = 3;
    }

    printf("%d", i);
}

So variables in PHP are not strictly block-scoped? In PHP, variables defined in inner block can be used in outer block?

powerboy
  • 10,523
  • 20
  • 63
  • 93

1 Answers1

59

PHP only has function scope - control structures such as if don't introduce a new scope. However, it also doesn't mind if you use variables you haven't declared. $i won't exist outside of main() or if the if statement fails, but you can still freely echo it.

If you have PHP's error_reporting set to include notices, it will emit an E_NOTICE error at runtime if you try to use a variable which hasn't been defined. So if you had:

function main() {
 if (rand(0,1) == 0) {
  $i = 3;
 }
 echo $i;
}

The code would run fine, but some executions will echo '3' (when the if succeeds), and some will raise an E_NOTICE and echo nothing, as $i won't be defined in the scope of the echo statement.

Outside of the function, $i will never be defined (because the function has a different scope).

For more info: http://php.net/manual/en/language.variables.scope.php

Chris
  • 10,337
  • 1
  • 38
  • 46
  • 5
    Good explanation! but just because you can do something doesn't mean you should. It's bad practice to use a variable that hasn't been defined. – Sheldon Juncker Jan 08 '15 at 16:15
  • Oh, and you don't need to check if the result of the rand call is equal to zero. You can simply put a shebang before rand :) – Peter Chaula Nov 09 '17 at 21:50