phpscopephp-include

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.


Solution

  • Use PHP namespaces:

    File1.php:

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

    File2.php:

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

    To access foo you have to use use:

    File2.php:

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