PHP understands the implementation principle by writing a template class yourself

*文
Release: 2023-03-18 10:12:01
Original
1197 people have browsed it

I believe many PHPers have come into contact with templates. How are templates implemented with their specific parsing syntax? This article lets everyone clearly understand the principle of templates by writing a simple template parsing class.

miniClass

class mini {
    public $template_dir = ''; // 模板文件存放的位置
    public $compile_dir = ''; // 模板文件编译后存放的位置
    public $array = array ();
    public function assign($key, $value) {
        $this->array [$key] = $value;
    }
    /*
     * 调动compile来编译模板,并自动引入;
     */
    public function display($template) {
        $comp = $this->compile ( $template );
        include ($comp);
    }
    /*
     * 传一个参数,读取那个html模板 流程:把模板读取过来,编译成php
     */
    public function compile($template) {
        // $template是一个html文件
        $temp = $this->template_dir . '/' . $template;
        $source = file_get_contents ( $temp );
        // 再把编译后的内容保存成.php文件
        $comp = $this->compile_dir . '/' . $template . '.php';
        // 判断模板是否已经存在,或者修改;
        if (file_exists ( $comp ) && filemtime ( $temp ) < filemtime ( $comp )) {
            return $comp;
        }
        $source = str_replace ( &#39;{$&#39;, &#39;<?php echo $this->array[\&#39;&#39;, $source );
        $source = str_replace ( &#39;}&#39;, &#39;\&#39;];?>&#39;, $source );
        // echo $source;
        file_put_contents ( $comp, $source );
        return $comp;
    }
}
Copy after login

Related recommendations:

##[Course] PHP underlying analysis video tutorial

php quick start summary

php concise function summary

The above is the detailed content of PHP understands the implementation principle by writing a template class yourself. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!