0

$user をクラス内に送信し、関数をレンダリングしてグローバル変数にする必要があります。

クラスとrender関数に「$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');
4

1 に答える 1

2

絶対に、絶対にグローバル変数を使用しないでください

それらはひどいものであり、コードをコンテキストにバインドし、副作用です.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クラスコンストラクターでプロパティを初期化します。

于 2013-10-21T10:49:45.300 に答える