Is it possible to define private variables in a PHP script so these variables are only visible in this single PHP script and nowhere else? I want to have an include file which does something without polluting the global namespace. It must work with PHP 5.2 so PHP namespaces are not an option. And no OOP is used here so I’m not searching for private class members. I’m searching for “somewhat-global” variables which are global in the current script but nowhere else.
In C I could do it with the static keyword but is there something similar in PHP?
Here is a short example of a “common.php” script:
$dir = dirname(__FILE__);
set_include_path($dir . PATH_SEPARATOR . get_include_path());
// Do more stuff with the $dir variable
When I include this file in some script then the $dir variable is visible in all other scripts as well and I don’t want that. So how can I prevent this?
There are a few things you could do to keep
$dirout of subsequent filesExample 1
This is the most obvious.
Example 2
Just unset the variable after defining it and using it. Note this will unset any variable named
$dirused prior to including this script.Example 3
It is less likely I suppose to redefine a global constant like this.
Example 4
You can define as many variables within that function and not affect the global namespace.
Conclusion
The first method is the easiest way to solve this problem, however because you want to use
$diragain, it may not be ideal. The last example will at least keep that$dir(and any others defined in that function) out of the global namespace.