Rumah  >  Artikel  >  pembangunan bahagian belakang  >  PHP从自己写个模板类来理解的实现原理

PHP从自己写个模板类来理解的实现原理

*文
*文asal
2017-12-23 17:17:421199semak imbas

相信很多PHPer都有接触过模板,模板以其特定的解析语法是如何实现的呢?本文通过自己写一个简单的模板解析类,来让大家清楚地认识模板的原理。

mini类

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;
    }
}

相关推荐:

[课程]PHP底层分析视频教程

php快速上手总结

php简洁函数小结

Atas ialah kandungan terperinci PHP从自己写个模板类来理解的实现原理. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn