Pseudo namespaces

    PHP 5.3 adds support for namespaces, but this version is still poorly distributed and unsuitable for industrial use in redistributable projects. In the meantime, the new version is on the way, I made a simple replacement of namespaces for variables.


    These functions can be used when you need to transfer variables from one included script to another, but it is not known what can happen to them along the way. At the end of the first script, we call the nsout () function with the space identifier and a list of variables that need to be saved, and before using these variables in the second script, we call nsin () with the space identifier.

    Copy Source | Copy HTML
    1. // Сохрняем переменные пространства имен
    2. function nsout($ns, $vars = array()) {
    3.     global $NS;
    4.     foreach ($vars as $var)
    5.         eval("global $$var; \$NS[\$ns][\$var] = $$var;");
    6. }
    7.  
    8. // Восстанавливаем переменные пространства имен
    9. function nsin($ns) {
    10.     global $NS;
    11.     $code = '';
    12.     if (!is_array($NS)) return;
    13.     foreach ($NS[$ns] as $name => $value)
    14.         $code .= "
                  global $$name;
                  $$name = " . php_var_map($value) . ";
              ";
    15.     eval($code);
    16. }
    17.  
    18. function php_var_map($var) {
    19.     if (!is_array($var))
    20.         return "'$var'";
    21.     else {
    22.         $code = '';
    23.         foreach ($var as $name => $value)
    24.             $code .= ($code ? ', ' : '') . "'$name' => " . php_var_map($value);
    25.         return "array($code)";
    26.     }
    27. }


    UPD: As suggested by homm, there are two great functions, compact () and extract (), which are just for this. So you can write like this:

    $NS['ns1'] = compact('var1', 'var2', 'var3');

    And then

    extract($NS['ns1']);

    In addition, the extract () function gives additional control over the extraction of variables, allowing you to add a prefix, and control conflicts.

    Also popular now: