2013-10-21 49 views
0

我需要发送$用户到类内部并渲染函数使其成为全局变量。将变量转换为全局类。 。 .PHP?

因为它不工作,除非我在类和渲染函数中写入“$ user”。

请帮帮我。

$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'); 
+0

为什么不建立一个构造函数来设置变量? –

+0

基本上,请参阅Alma Do Mundos的答案 –

回答

2

永远,永远使用全局变量

他们是可怕的,他们是你的代码绑定到上下文和它们的副作用 - 如果你在2054条线的某处改变你的变量第119个包含的文件,您的应用程序的行为将会改变,然后祝您好运并调试。

相反,你应该要么通过你的用户在方法的参数:

public function render($template_name, $user) 

或类实例创建属性:

class Template 
{ 
    protected $user = null; 

    public function render($template_name) 
    { 
    //access to $this->user instead of $user 
    } 
    //... 
} 

-and,当然,在constructor类初始化$user属性。