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!
You need to understand how
variable scopeworks. 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:
Then, pass the variables when calling setView:
This will create variables named
$oneand$twoinside 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.