9

i'm confused about the php variable scope. such as:

while(true){
    $var = "yes , it is a test!";
  }
  printf($var)

the $var is defined in while statement scope , how could we get it outside it's scope ? and i can't find explanation on the document .

i wonder how php deal with it's scope .

Bastardo
  • 4,144
  • 9
  • 41
  • 60
mike
  • 1,127
  • 4
  • 17
  • 34
  • 3
    `while (true)` is an infinity loop... – RobertO Apr 12 '11 at 07:51
  • Please go back and review your old questions. If there are good sollutions, mark them as accepted using the green 'check'. If there are none (which i doubt), please consider answering your own questions with how you solved the problems in the end. Furthermore, try and check your formatting. – Nanne Apr 12 '11 at 07:52
  • This might be a useful starting point: http://php.net/manual/en/language.variables.scope.php – Will Vousden Apr 12 '11 at 07:53
  • how about switch() case statement? Does it create its own scope like a function? Thanks~ – user798033 Oct 23 '11 at 21:21
  • if you want to create a new local scope http://stackoverflow.com/a/33460057/3160597 – azerafati Nov 01 '15 at 07:21

6 Answers6

8

while is not a function. scope of variable refers to variable inside functions and classes

S L
  • 14,262
  • 17
  • 77
  • 116
6

In PHP, a while loop doesn't create a new scope. So it will be available in the function

Ikke
  • 99,403
  • 23
  • 97
  • 120
3

If you do while(true) you will not get out of the while, so it wouldn't matter. But if you would have a real expression, something like this (this is a useless example, i know)

$i=0
while($i<10){ 
   $var = "yes , it is a test!"; 
   $i++;
 } 
 printf($var);

Will just work. There is no special "while" variable scope, the printf will print your string. check : http://php.net/manual/en/language.variables.scope.php

Nanne
  • 64,065
  • 16
  • 119
  • 163
2

Loop does not have any scope in PHP. variable is simply available outside the loop.

just echo outside the loop;

echo $var;

Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
0

Notice: Different PHP-version behave differently on $GLOBALS, $_SERVER ($HTTP_SERVER_VARS [deprecated]) and $_SESSION. Please check that. Old PHP page are not always upwards compatible. You should check that.

davidS
  • 31
  • 4
0

For the complete answer check the documentation:

http://php.net/manual/en/language.variables.scope.php

qbert220
  • 11,220
  • 4
  • 31
  • 31