【问题标题】:PHP requiring templates that use global variablesPHP 需要使用全局变量的模板
【发布时间】:2014-06-23 20:32:12
【问题描述】:

我正在尝试重构一些代码,并且有使用全局变量的模板。函数内部的require 和include 只使用局部作用域,那么有没有办法“要求全局”?

现在,我们有相当多的代码行在所有路由器文件中重复,就像这样。本期所指的声明:

require 'header.php';
require $template;
require 'footer.php';

这些语句可以在全局范围内找到。我正在尝试将这些重构为这样的类中的方法:

class Foo {

    /**
     * Template file path
     * @var string
     */
    protected $template;

    public function outputHTMLTemplate() {
        header("Content-Type: text/html; charset=utf-8");
        require 'header.php';
        if (file_exists($this->template)) {
            require $this->template;
        }
        require 'footer.php';
    }

}

假设我有template.php,在模板里面有像这样的超全局变量和全局变量:

<h1>Hello <?= $_SESSION['username']; ?></h1>
<ul>
<?php
foreach ($globalVariable1 as $item) {
    echo "<li>$item</li>";
}
?>
</ul>

这是一个简化的例子,在实际的模板中可能会有很多全局变量。

我应该如何将输出代码移动到方法中?

【问题讨论】:

    标签: php scope require


    【解决方案1】:

    您可以尝试使用extract php 函数。它将使所有全局变量对包含的文件可用,就像它被包含在全局范围内一样。

    <?php
    
    $myGlobal = "test";
    
    class Foo {
    
        /**
         * Template file path
         * @var string
         */
        protected $template;
    
        public function outputHTMLTemplate() {
             extract($GLOBALS);
    
             header("Content-Type: text/html; charset=utf-8");
             require 'header.php';
             if (file_exists($this->template)) {
                 echo $myGlobal; // Prints "test"
                 require $this->template;
             }
             require 'footer.php';
        }
    
    }
    
    $x = new Foo();
    $x->outputHTMLTemplate();
    

    【讨论】:

      【解决方案2】:

      Superglobals 已经可用。对于其他变量,这是一些额外的工作,但正常的方法是这样的:

      protected $data;
      protected $template;
      
      public function outputHTMLTemplate() {
           header("Content-Type: text/html; charset=utf-8");
           require 'header.php';
           if (file_exists($this->template)) {
               extract($this->data);
               require $this->template;
           }
           require 'footer.php';
      }
      
      public function setData($var, $val) {
          $this->data[$var] = $val;
      }
      

      $foo->setData('globalVariable1', $globalVariable1);
      

      【讨论】:

      • 这是不可行的,因为全局变量的数量可能会在运行时发生变化。会使用$GLOBALS 工作(即public function __construct() { $this-&gt;data = $GLOBALS; })吗?
      • 这不是很安全,但是是的,看看@Christian 的回答。
      猜你喜欢
      • 1970-01-01
      • 2023-03-19
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 2014-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多