【问题标题】:losing the scope of an object inside an included file丢失包含文件中对象的范围
【发布时间】:2018-09-30 13:45:29
【问题描述】:

我试图在一个包含文件中调用一个对象的方法,该包含文件本身被加载到类中,输出缓冲区如下所示:

public function render($file){

    ob_start();
    require_once($file);
    $this->template = ob_get_contents();
    ob_end_clean();

    return $this->template;
}

得到这些错误:

Notice: Undefined variable: template
Fatal error: Call to a member function showTitle() on a non-object

包含的文件是作为模板使用的,会有很多。当用作static 属性和方法集时它可以正常工作,但不能与实例化对象的属性和方法集一起使用,这是必需的方式。

以下是供您查看的所有测试文件。

类文件“classTest.php”:

<?php
    // classTest.php

    class Test{

    protected $template;
    protected $title =  "Title";
    static    $titleStatic = "Title Static";

    public function render($file){

        ob_start();
        require_once($file);
        $this->template = ob_get_contents();
        ob_end_clean();

        return $this->template;
    }

    public function showTitle(){
        return $this->title;
    }

    static function showTitleStatic(){
        return self::$titleStatic;

    }
}
?>

测试文件“test.php”:

<?php
    // test.php

    require_once 'classTest.php';

    $template = new Test;

    echo $template->showTitle();

    $templateFile = 'includeTest.php';

    echo $template->render($templateFile);

?>

包含文件“includeTest.php”:

<!--    includeTest.php     -->

<div id="container">
    <div id="titleStatic"><?php echo Test::showTitleStatic(); ?></div>
    <div id="title"><?php echo $template->showTitle(); ?></div>
</div>

【问题讨论】:

    标签: php class oop object static


    【解决方案1】:

    将您的 includeTest.php 更改为:

    <div id="container">
        <div id="titleStatic"><?php echo Test::showTitleStatic(); ?></div>
        <div id="title"><?php echo $this->showTitle(); ?></div>
    </div>
    

    您调用的 $template 应该是 $this,因为它是在类内部而不是从外部填充的。

    【讨论】:

      猜你喜欢
      • 2012-09-06
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      相关资源
      最近更新 更多