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.

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

报告相同问题?

悬赏问题

  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多