我正在开发一个cms,我希望设计师能够在使用名为$ view的对象时调用所有内容。我的问题是包含的模板文件不能再访问$ view-object了。
视图对象包含page_title(),...等内容。 我也使用模板,所以我希望设计师能够通过访问$ view对象来调用正确的模板。
备份我的解释的一些代码:
我的图书馆:
class view {
function page_title() {}
function template() {
$this->template = new template;
$this->template_include = $this->template->template_include();
}
}
class template {
function template_include(){
include('template.php');
}
}
我的索引文件:
$view = new view;
$view->template();
我的template.php:
$view->page_title();
但是我遇到了一个问题:创建了视图对象,然后使用视图类中的方法调用了一个对象,该对象使用方法template_include()包含正确的template.php。在这个模板中,我再次使用view-object,以便调用正确的标题,内容,...... 我的问题是包含的模板文件不能再访问$ view-object。
猜猜大家都知道错误: 致命错误:在非对象上调用成员函数field_title()
我致力于为设计人员/用户尽可能简化这个cms,所以我只希望view-object调用所有内容,而不需要在模板文件中添加额外的内容......
谢谢!
答案 0 :(得分:4)
您可以将$view
传递给方法/类
索引
$view = new view;
$view->template($view);
类
class view {
function page_title() { echo "this works!!!";}
function template($view) {
$this->template = new template;
$this->template_include = $this->template->template_include($view);
}
}
class template {
function template_include($view){
include('template.php');
}
}
答案 1 :(得分:0)
您是否曾尝试全局声明$ view-object?
将global $view;
放入index.php
以及template.php
,希望它可以解决您的问题!
答案 2 :(得分:0)
如果要在函数中包含模板文件,则使用此函数的范围解释此文件的内容。解决它的最佳方法是将关联数组传递给此函数,并使用此范围内的变量,即:
class view {
function page_title() {}
function template(array $variables) {
$this->template = new template;
$this->template_include = $this->template->template_include($variables);
}
}
class template {
function template_include(array $variables){
if($variables){
extract($variables);
}
include('template.php');
}
}
现在通过这样调用,您可以访问模板中的$view
和$title
个变量:
$view = new view;
$vars = array(
'view' => $view,
'title' => 'some title'
);
$view->template($vars);