【发布时间】:2014-10-15 18:10:48
【问题描述】:
我有一个 PHP 类,可以更轻松地插入我创建的模板...
即
...
/*Get Templates*/
public function template($file){
if(isset($file) && file_exists($file.".php")){
$controller = $this;
include $file.".php";
}else{
echo "";
}
}
它位于public_html之外的目录中
kms/php_includes/kms.php
但如果我在我的索引页面中使用它
public_html/index.php
我在索引中设置的变量在模板中都不起作用?
例子
index.php
$user = "Mr.EasyBB";
$controller->template("../kms/site/header");//$controller is the class variable
header.php
echo $user; //this doesn't work
$controller->template("../kms/site/svg/smile"); //this still works
但是在kms/site/header.php
我将undefined variable user 定向到头php 文件。这是因为模板的来源不在public_html 之外,还是我在这里做了一些愚蠢的事情而没有意识到。
在我看来,问题在于文件的位置在完全不同的目录中,所以我的简单做法是添加一个集合并获取。
...
private $variables = array();
public function get($prop){
if($this->variables[$prop]){
return $this->variables[$prop];
}
}
public function set($prop=null,$val=null){
if($prop !== null && $val !== null){
$this->variables[$prop] = $val;
}
}
/*Get Templates*/
public function template($file){
if(isset($file) && file_exists($file.".php")){
$controller = $this;
foreach($this->variables as $var->$val){
//i need to assign explicitly the $var name here hence why I used double dollar signs. But it's not working either.
$$var = $val;
}
include $file.".php";
}else{
echo "";
}
}
【问题讨论】:
标签: php class include undefined