【发布时间】: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