试着写一个PHP模板类 – 这感觉不对
发布时间:2020-12-13 21:43:42 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试学习一些关于 PHP的东西并编写我自己的模板类.但它感觉无效.这样做会不会影响性能?如果可以的话,看一看是什么问题: ?class Template { private $file,$template,$data; public function __construct($file) { $this-template = file_get_content
我正在尝试学习一些关于
PHP的东西并编写我自己的模板类.但它感觉无效.这样做会不会影响性能?如果可以的话,看一看是什么问题:
<? class Template { private $file,$template,$data; public function __construct($file) { $this->template = file_get_contents('views/wrapper.php'); $this->file = file_get_contents('views/'.$file.'.php'); } public function __set($key,$val) { $this->data[$key] = $val; } public function __get($key) { return $this->data[$key]; } private function replaceAll() { foreach($this->data AS $key => $val) $this->template = str_replace('@'.$key,$val,$this->template); $this->template = str_replace('{LOAD}',$this->file,$this->template); } public function render() { $this->replaceAll(); echo $this->template; } } ?> 我想使用包含页脚标题的包装器,其中包含侧栏/导航.所以我需要以某种方式在那里动态设置一个活动类,然后我希望能够基于构造函数或类似的东西加载视图.我正在做什么..好吗? 解决方法
__get和__set函数非常慢.字符串替换也很慢.你为什么用这种方式制作模板?如果你做了更像这样的事情怎么办?
模板类 class template { protected $templateFile; public function __construct($template_file) { $this->templateFile = $template_file; } public function render() { require($this->templateFile); } } 模板文件 <html> <p><?= $this->someProperty ?></p> </html> 用法 $view = new template($template_file_path); $view->someProperty = 'hello world'; $view->render(); 唯一的缺点是编写模板的人也可以访问编写PHP. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |