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

5

9

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

Swanson answered 30/3, 2010 at 3:29 Comment(0)
L
12

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.

London answered 30/3, 2010 at 3:31 Comment(1)
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.Indianapolis
P
1

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

Petuu answered 30/3, 2010 at 3:31 Comment(0)
D
1

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.

Dillie answered 30/3, 2010 at 3:34 Comment(0)
P
1

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
}
?>
Photolysis answered 30/3, 2010 at 3:41 Comment(3)
Note: I'm not saying this is a good idea to do, it just illustrates my point well.Photolysis
This feature is extremely useful for automatically generated code, but I'd rather not read or write that myself.London
So gross. But hey PHP was way ahead of JSX :DAlcoholic
H
0

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.

Hepatica answered 30/3, 2010 at 3:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.