Reputation: 5389
Is it possible to do something similar to the using
keyword in C# (and probably others) to limit variable scope? I'm experimenting with database connection patterns, and am currently trying to get this to work:
$db = array(
"server" =>"localhost",
"user" =>"root",
"pass" =>"my_password",
"database" =>"my_database"
);
$pdo = null;
{ // ??? These seem to be completely ignored, no errors, no effect at all
extract($db);
$pdo = new PDO("mysql:host=$server;dbname=$database", $user, $pass);
}
//Do database stuff
I'm using extract
, which is normally a bad idea, so I'm trying to protect whatever it returns where those curly braces are. In C# I could probably do something like using (extract($db)) { ... }
and whatever extract
returns would be limited to that scope, but I can't figure out if this is possible in PHP. I'm not even sure if PHP disposes of variables.
Upvotes: 2
Views: 587
Reputation: 14596
Instead of code blocks, IIFEs, or "Immediately invoked function expressions" could be used in PHP too if necessary – they're not just for JavaScript:
https://en.wikipedia.org/wiki/Immediately_invoked_function_expression
$x = 1; // global var
$y = 2; // global var
echo "x={$x}, y={$y}\n";
// PHP 5.3+
call_user_func(function()use( & $x ){
$x = 33; // reference to the global var because use( & $x )
$y = 44; // local var
echo "x={$x}, y={$y}\n";
});
// PHP 7+
(function()use( & $x ){
$x = 555; // reference to the global var because use( & $x )
$y = 666; // local var
echo "x={$x}, y={$y}\n";
})();
echo "x={$x}, y={$y}\n";
Output:
x=1, y=2 // initial global var values
x=33, y=44 // inside the first PHP5.3+ iife
x=555, y=666 // inside the second PHP7+ iife
x=555, y=2 // the global variables after executing both
Upvotes: -1
Reputation: 9417
Since PHP >= 5.3
you can use Namespaces like this:
// per file
namespace App\One
$var = 1;
// or, per block
namespace App\Two {
$var = 2;
}
Then later you can call it like this -- there are other ways as well:
echo \App\Two\var;
Update
Well, it seems that variables
are not affected by namespace
.
Although any valid PHP code can be contained within a namespace, only the following types of code are affected by namespaces: classes (including abstracts and traits), interfaces, functions and constants.
But what you can still do is to use Constants instead:
namespace App\One;
define('App\One\ABC', 'abc'); // specified namespace
define(__NAMESPACE__ . '\XYZ', 'xyz'); // current namespace -- which is App\One here
Upvotes: 0