【问题标题】:PHP scope of $this in included file in class method类方法中包含文件中 $this 的 PHP 范围
【发布时间】:2015-02-18 14:26:56
【问题描述】:

我的一个类中有一个方法,看起来像,

public function render() {

    foreach ($this->_levels as $level) {

        ob_start();

        $path = $_SERVER['DOCUMENT_ROOT'] . '/' . $level[0] . '/' . $level[1] . '.php';

        if (file_exists($path)) {

            require($path);
        }

        $content = ob_get_clean();

        if ($content) {

            $this->_content = $content;
        }
    }

    return $this->_content;
}

在包含的文件中,我可以访问$this。无论如何,我可以使这种情况不发生吗? (所以$this没有定义?)

我尝试将它包装在一个匿名函数中并绑定到 null 但它不起作用。

【问题讨论】:

  • 你想删除 $this->_levels 和 $this->_content 的使用?
  • 不,包含的文件在$this的范围内,我想从包含的文件中删除对象范围,(好像它是从类方法之外包含的一样)跨度>
  • 那么就不要包含那个文件。还有其他方法可以注入数据/代码/任何东西。因此:XY 问题。你想要实现什么(即当你想出在类方法定义中包含一个文件的想法时,你试图解决什么?)?

标签: php class methods instance


【解决方案1】:

你可以在你的类之外创建一个新函数并从那里require你的文件。 Composer 在他们的ClassLoader.php 中这样做了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-06
    • 1970-01-01
    • 1970-01-01
    • 2016-03-11
    • 2016-12-08
    • 2010-10-06
    • 2016-01-31
    • 1970-01-01
    相关资源
    最近更新 更多