【问题标题】:How does the lithium PHP framework generate a $this context in a PHP page?锂PHP框架如何在PHP页面中生成$this上下文?
【发布时间】:2012-11-22 09:59:47
【问题描述】:

我一直在调查Lithium PHP Framework,但我不明白它是如何设置$this->context; (particularly in this layout.)

由于您不能简单地重新分配$this,显然这个布局会在某些时候被包含在内,更让我困惑的是他们在类定义之外使用$this

我已经有一段时间没有编写 PHP 代码了,所以请在这里帮助我。

【问题讨论】:

    标签: php frameworks views lithium


    【解决方案1】:

    让我印象深刻的第一个想法是这个模板页面是从一个方法调用的。

    class Viewer
    {
        public $html;
        private $title;
        private $content;
    
        public function __construct()
        {
            $this->html = new \Utilities\HTMLBag();
        }
        public function loadView($template)
        {
            ob_start();
            include 'path/to/views/'.$template.'.php';
            $this->content = ob_get_clean();
        }
        public function title()
        {
            return $this->title;
        }
    }
    

    至此,包含的$template可以访问Viewer类的任意方法

    【讨论】:

    • 是的,这就是 Lithium 的工作方式。这也是几乎所有使用 PHP 模板的 PHP 框架和模板库都是这样做的。
    【解决方案2】:

    很简单:通过在类的方法内部调用 include/require。

    文件A.php:

    <?php
    class A {
        public $test = 'Hello';
    
        public function xyz() {
            include 'B.php';
        }
    }
    

    文件 B.php:

    <html>
        <body><?php echo $this->test; ?></body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-29
      • 2023-03-31
      • 2010-10-22
      • 2017-09-06
      • 2010-11-08
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      相关资源
      最近更新 更多