douzepao0281 2018-04-19 23:04
浏览 73
已采纳

丢失包含文件中对象的范围

Am trying to call an object's method inside of an included file which the included file itself, was loaded in the class with output buffer like below:

public function render($file){

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

    return $this->template;
}

Getting these errors:

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

The included file is to be used as a template and there will be many. It works fine when used as static property and method set, but not with the instantiated object's property and method set which is the required way.

Below are all test files for your review.

Class file "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 file "test.php":

<?php
    // test.php

    require_once 'classTest.php';

    $template = new Test;

    echo $template->showTitle();

    $templateFile = 'includeTest.php';

    echo $template->render($templateFile);

?>

Include file "includeTest.php":

<!--    includeTest.php     -->

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

1条回答

  • dpmkif3097 2018-04-19 23:38
    关注

    Change your includeTest.php to this:

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

    Your calling $template when it should be $this since it's being populated inside the class not from outside.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站