views:

79

answers:

5

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

+5  A: 

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.

zneak
Re: "The only scoping notion in PHP exists for functions or methods", PHP 5.3 and namespaces kind of turn that statement on its ear.
Alan Storm
+1  A: 

No, by default all files share the same scope in PHP. The only scoping you get is by using classes or functions.

WoLpH
A: 

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.

Adrian A.
+1  A: 

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.

silent
thanks for info
ggfan
+1  A: 

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
}
?>
crimson_penguin
Note: I'm not saying this is a good idea to do, it just illustrates my point well.
crimson_penguin
This feature is extremely useful for automatically generated code, but I'd rather not read or write that myself.
zneak