我正在尝试仅在 1 个数组中循环所有分配,但出现如下图所示的错误,谁能教我怎么做?为什么会出现此错误?非常感谢
这是我的 template.php
class Template{
private $vars = array();
public function assign($key, $value){
$this->vars[$key] = $value;
}
public function render($template_name){
$path = $template_name. '.html';
if(file_exists($path)){
$contents = file_get_contents($path);
foreach($this->vars as $key => $value){
$contents = preg_replace('/\[' . $key . '\]/', $value, $contents);
}
$pattern = array(
'/\<\!\-\- if (.*) \-\-\>/',
'/\<\!\-\- else \-\-\>/',
'/\<\!\-\- endif \-\-\>/',
'/\<\!\-\- echo (.*) \-\-\>/'
);
$replace = array(
'<?php if($1) : ?>',
'<?php else : ?>',
'<?php endif; ?>',
'<?php echo ($1) ?>'
);
$contents = preg_replace($pattern, $replace, $contents);
eval(' ?>' . $contents . '<?php ');
}else {
exit('<h1>Template error!</h1>');
}
}
}
?>
assign 用于分配 value ,然后在我的 html 中可以只写 [value] 来显示它的值
头文件.php
<?php
session_start();
header('Content-Type: text/html; charset=utf-8');
include $_SERVER['DOCUMENT_ROOT'] . '/class/template.php';
$game = '2';
$tech = '3';
$beauty = '4';
$bagua = '1';
$template = new Template;
$template->assign('sitename', 'site name');
$template->assign('title', '');
$code = array(
'test1',
'test2',
'test3'
);
$word = array(
'haha1',
'haha2',
'haha3'
);
$template->assign($code, $word);
$template->assign('test4', 'haha4');
$template->render('view/default/header');
?>
header.html
[test1][test2][test3][test4]
结果: