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 }