Reputation: 21
I need to send $user to inside the class and render function to make it global variable.
because it not work unless i write "$user" in the class and render function.
Please help me.
$user = 'admin';
class Template{
public function render($template_name)
{
global $user;
$path = $template_name . '.html';
if (file_exists($path))
{
$contents = file_get_contents($path);
function if_condition($matches)
{
$parts = explode(" ", $matches[0]);
$parts[0] = '<?PHP if(';
$parts[1] = '$' .$parts[1]; // $page
$parts[2] = ' ' . '==' . ' ';
$parts[3] = '"' . substr($parts[3], 0, -1) . '"'; //home
$allparts = $parts[0].$parts[1].$parts[2].$parts[3].') { ?>';
return $allparts.$gvar;
}
$contents = preg_replace_callback("/\[if (.*?)\]/", "if_condition", $contents);
$contents = preg_replace("/\[endif\]/", "<?PHP } ?>", $contents);
eval(' ?>' . $contents . '<?PHP ');
}
}
}
$template = new Template;
$template->render('test3');
Upvotes: 0
Views: 227
Reputation: 37365
Never, never use global variables
They are awful, they bind your code to context and they are side-effect - if you'll change your variable somewhere in 2054-th line of 119-th included file, the behavior of your application will change and then good luck with debugging that.
Instead you should either pass your user in method's parameters:
public function render($template_name, $user)
or create property in class instance:
class Template
{
protected $user = null;
public function render($template_name)
{
//access to $this->user instead of $user
}
//...
}
-and, of course, initialize $user
property in class constructor.
Upvotes: 2