Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable scope difference between PHP and C: block scope is not exactly the same?

Tags:

c

scope

php

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?

like image 973
powerboy Avatar asked May 24 '10 00:05

powerboy


People also ask

What are the different scopes of variables in PHP?

PHP has three types of variable scopes: Local variable. Global variable. Static variable.

Is PHP variable block scope?

A local scope is a restricted boundary of a variable within which code block it is declared. That block can be a function, class or any conditional span. The variable within this limited local scope is known as the local variable of that specific code block. The following code block shows a PHP function.

What is variable and scope of variable in PHP?

In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of the script where the variable can be referenced/used. PHP has three different variable scopes: local.

What are the different scope of variables?

There are mainly two types of variable scopes: Local Variables. Global Variables.


1 Answers

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

like image 105
Chris Avatar answered Sep 16 '22 16:09

Chris