phpscope

How to limit variable to a local scope?


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.


Solution

  • 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