• PHP 生成 Html


     1 <?php
     2 
     3 /**
     4 
     5 生成:<form id="form"><label><b>用户名:</b><input name="usrname"></label></form>
     6 
     7 $form = Html::tag('form')->attr(['id' => 'form']);
     8 $label = Html::tag('label');
     9 $b = Html::tag('b');
    10 $input = Html::tag('input')->attr('name', 'usrname');
    11 
    12 echo $form->add($label->add($b->add('用户名:'))->add($input))->make();
    13 
    14 */
    15 
    16 class Html{
    17 
    18     protected static $init = null;
    19     protected $attr = [];
    20     protected $tag = '';
    21     protected $elements = [];
    22     public $closings = ['br', 'hr', 'input', 'source', 'area', 'base', 'link', 'img', 'meta', 'basefont', 'param', 'col', 'frame', 'embed'];
    23 
    24     protected function __construct($tag){
    25 
    26         $this->tag = $tag;
    27     }
    28 
    29     public static function tag($value){
    30 
    31         return new static($value);
    32     }
    33 
    34     public function attr($name, $value = ''){
    35 
    36         if(is_array($name)){
    37             $this->attr = $name + $this->attr;
    38         }else{
    39             $this->attr[$name] = $value;
    40         }
    41 
    42         return $this;
    43     }
    44 
    45     public function add($element){
    46 
    47         $this->elements[] = $element;
    48         return $this;
    49     }
    50 
    51     public function make(){
    52 
    53         $attr = array_reduce(array_keys($this->attr), function($carry, $item){
    54             $carry .= ' ' .$item . '=' . '"'.$this->attr[$item] .'"' ;
    55             return $carry;
    56         });
    57 
    58         $html = '<'.$this->tag. $attr.'>';
    59         //遍历子元素调用 make 方法,形成递归
    60         foreach ($this->elements as $element){
    61 
    62             if(is_object($element)){
    63                 $element = $element->make();
    64             }
    65             $html .= $element;
    66         }
    67 
    68         if(!in_array($this->tag, $this->closings)) $html .= '</'.$this->tag.'>';
    69 
    70         return  $html;
    71 
    72     }
    73 
    74 
    75 }
  • 相关阅读:
    继承实战
    工厂设计模式
    接口匿名内部类
    枚举类
    接口.匿名内部类
    学生信息管理系统(bug)
    System类
    1.1 计算机基础知识 & jdk 安装 & 标识符
    DedeCMS 在子栏目或内容页,调用所在顶级栏目的栏目名
    latex 中 section 标题中如何插入特殊符号
  • 原文地址:https://www.cnblogs.com/zbseoag/p/12717290.html
Copyright © 2020-2023  润新知