类包括不让变量在模板中工作

时间:2014-10-15 18:10:49

标签: php class include undefined

我有一个PHP类,可以更容易地插入我创建的模板......

...
 /*Get Templates*/
 public function template($file){
       if(isset($file) && file_exists($file.".php")){
          $controller = $this;
          include $file.".php";
       }else{
          echo "";
       }
    }

位于public_html以外的目录中

kms/php_includes/kms.php

但如果我在索引页面中使用它

public_html/index.php

我在索引中设置的所有变量都不在模板中工作吗?

实施例

的index.php

$user = "Mr.EasyBB";
$controller->template("../kms/site/header");//$controller is the class variable

的header.php

echo $user; //this doesn't work
$controller->template("../kms/site/svg/smile"); //this still works

但在kms/site/header.php

我将undefined variable user定向到标题php文件。这是因为模板的来源是public_html之外还是我在这里做了些蠢事而没有实现它。

对我来说,问题是文件位于完全不同的目录中,所以我的琐碎做法是添加一个集合并获取。

 ...
 private $variables = array();

 public function get($prop){
    if($this->variables[$prop]){
       return $this->variables[$prop];
    }
 }
 public function set($prop=null,$val=null){
   if($prop !== null && $val !== null){
       $this->variables[$prop] = $val;
     }
 }

 /*Get Templates*/
 public function template($file){
       if(isset($file) && file_exists($file.".php")){
          $controller = $this;
          foreach($this->variables as $var->$val){
             //i need to assign explicitly the $var name here hence why I used double dollar signs. But it's not working either.
             $$var = $val;
          }
          include $file.".php";
       }else{
          echo "";
       }
    }

1 个答案:

答案 0 :(得分:1)

这两个文件无法相互通信,因为它们有两个不同的范围;它们包含在两个单独的template()

调用中

尝试在$controller->user内设置index.php并在header.php中重复使用。

// controller
function template() {
    $this->user = 'Foo';
    include 'header.php'; // tells php to use header.php as if
                          // it were just more code for this function
}

// header.php
echo $this->user; // Foo

您还可以将变量存储在数组中,并在包含标题之前将其解压缩。

// controller
function template() {
    $this->templateVars['user'] = 'Foo';
    extract($this->templateVars);
    echo $user; // Foo
    include 'header.php';
}

// header.php
echo $user; // Foo

我建议不要这样做,但是,如果您的模板很大并且创建了自己的模板,那么您可以轻易忘记变量的来源。但是如果需要,可以将提取的变量名全部用大写表示它们来自控制器。

$this->templateVars['USER'] = 'Foo'; // etc
相关问题