将类中的变量转换为全局变量. . ..php


Convert Variable to global in the class . . .php?

我需要将$user发送到类内部并渲染函数以使其成为全局变量。

因为除非我在类和渲染函数中编写"$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');

永远不要,永远不要使用全局变量

它们

很糟糕,它们将您的代码绑定到上下文中,并且它们是副作用 - 如果您将第 119 个包含的文件的第 2054 行中的某个位置更改变量,则应用程序的行为将发生变化,然后祝您好运调试它。

相反,您应该在方法的参数中传递用户:

public function render($template_name, $user)

或在类实例中创建属性:

class Template
{
   protected $user = null;
   public function render($template_name)
   {
     //access to $this->user instead of $user
   }
   //...
}

-当然,在类构造函数中初始化$user属性。