If yes is there any way to ac开发者_Go百科cess a var defined in another PHP code snippet tag?
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.
No, by default all files share the same scope in PHP. The only scoping you get is by using classes or functions.
Variable scope in PHP doesn't work like that.
Variable score is working in classes and functions. For example:
<?php $a = 10 ?>
<?php echo $a; ?>
This will work.
However:
<?php
$a = 10;
function get_a(){
echo $a;
}
?>
This one will not work. It's either not showing $a value or NOTICE level error (depending on your configuration)
For more info, you can see this page.
You can think of the parts of the script that AREN'T inside <?php ?>
as equivalent to an echo statement, except without any interpolation of variables, quotes, etc. - only <?php ?>
. So for instance, you can even do something like this:
<?php if (42) { ?> This will only be output if 42 is true. <?php } ?>
If you have
<php
$a = '111';
?>
and
<php
echo $a
?>
in the same page, it will output 111, meaning, it recognizes the variables from the first PHP snippet.
精彩评论