HittmanA HittmanA - 1 month ago 6
PHP Question

How to prevent variables from being used when a file is include() ed

The title is a little confusing, I know. Basically I want to prevent a variable in one file which I include() into another file form being used.
Example:

File1.php:

<?php
$foo = "Bar";
?>


File2.php:

<?php
include("File1.php");
echo $foo;
?>


In the above example File2.php will obviously echo "Bar"; however, I want to prevent this from happening while still being able to access any functions inside File1.php. Ideally variables declared outside of functions should not be accessible when the file is included() ed.

Answer

Use PHP namespaces:

File1.php:

<?php
namespace baz {
    $foo = "Bar";
}
namespace { // global code
$x = "XXX";
}
?>

File2.php:

<?php
include("File1.php");
echo $x; // outputs XXX
echo $foo; // Undefined variable: foo
?>

To access $foo you have to use use:

File2.php:

<?php
include("File1.php");
use baz;
echo $foo; // outputs Bar
?>
Comments