1

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.

Any insight to this problem is much appreciated!

Gumbo
  • 643,351
  • 109
  • 780
  • 844
Scott
  • 5,338
  • 5
  • 45
  • 70

1 Answers1

1

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.

source

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
Mahdi
  • 9,247
  • 9
  • 53
  • 74
  • I guess that's the only other way to limit scope in PHP... thank you! – Scott Dec 29 '13 at 21:32
  • No. Variables [aren't](http://stackoverflow.com/questions/5287315/can-php-namespaces-contain-variables) bound to namespaes. – mario Dec 30 '13 at 01:06
  • @mario Thanks mario for the correction, I didn't know that. I've updated the answer as well. – Mahdi Dec 30 '13 at 09:00