2

I've a problem with getting a variable in a file, which is included through a static class method.

one.php:

require_once("classes/tools.class.php");

$variable = "variable";

Tools::setView("test");

tools.class.php:

class Tools{    

    public static function setView($viewName){
        if(!is_file("views/" . $viewName . ".php")){
            echo "Chyba pri nacitani view: \"$viewName\" v " . $_SERVER["SCRIPT_NAME"];
            die();
        }
        else{           
            include "views/" . $viewName . ".php";
        }

    }

}

view/test.php:

echo $variable;

After "echo" i got the "Undefined variable" error.

Can somebody help me with this problem, please?

Thanks!

Crylvarrey
  • 109
  • 2
  • 6

1 Answers1

2

You need to understand how variable scope works. In this case, your variable can't be seen inside the view script because the view script is being executed inside a function, and the function does not have access to variables in the global scope. You could declare the variable as global inside the function, but that is not recommended -- and impractical when you don't know ahead of time what variables are going to be set.

Ideally, you'll want to inject the variables that will be used by the view script into the call that sets up the view. Perhaps something like this:

public static function setView($viewName, $vars) {

    // loop through the passed vars and set them in the local scope
    extract($vars);

    // render the view
    include "views/" . $viewName . ".php";
}

Then, pass the variables when calling setView:

$vars = array(
    'one' => 1,
    'two' => 2
);
Tools::setView('test', $vars);

This will create variables named $one and $two inside the function scope, which can then be used as normal in your view script. In addition, it isolates the view from being "poisoned" by other incidental variables that might happen to exist in your program. I.e., only the variables that you explicitly pass to the method call will be usable in the view script.

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98
  • Psst: [`extract`](http://php.net/manual/en/function.extract.php) ;) - and to reduce side-effects: http://stackoverflow.com/a/7697490/367456 – hakre Sep 23 '12 at 16:42