Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does every PHP code snippet inside the <?php> tag have its own variable scope?

If yes is there any way to access a var defined in another PHP code snippet tag?

like image 812
johnk Avatar asked Mar 30 '10 03:03

johnk


1 Answers

No, they don't. Separate <?php ?> tags share the same variable scope. You can access any variable declared from any scope:

<?php $foo = 4; ?>
<?php echo $foo; /* will echo 4 */ ?>

The only scoping notion in PHP exists for functions or methods. To use a global variable in a function or a method, you must use the $GLOBALS array, or a global $theVariableINeed; declaration inside your function.

like image 139
zneak Avatar answered Oct 22 '22 06:10

zneak