我正在用PHP编写一个HTML类,这样我们就可以保持所有HTML输出的一致性。然而,我很难理解其中的逻辑。我用PHP工作,但任何语言的答案都可以。
我希望类能够正确嵌套标签,所以我希望能够这样调用:
$html = new HTML;
$html->tag("html");
$html->tag("head");
$html->close();
$html->tag("body");
$html->close();
$html->close();
<head>
在...下面
<html>
,但我不太明白其中的逻辑。以下是实际的代码
HTML
类的现状:
class HTML {
/**
* internal tag counter
* @var int
*/
private $t_counter = 0;
/**
* create the tag
* @author Glen Solsberry
*/
public function tag($tag = "") {
$this->t_counter = count($this->tags); // this points to the actual array slice
$this->tags[$this->t_counter] = $tag; // add the tag to the list
$this->attrs[$this->t_counter] = array(); // make sure to set up the attributes
return $this;
}
/**
* set attributes on a tag
* @author Glen Solsberry
*/
public function attr($key, $value) {
$this->attrs[$this->t_counter][$key] = $value;
return $this;
}
public function text($text = "") {
$this->text[$this->t_counter] = $text;
return $this;
}
public function close() {
$this->t_counter--; // update the counter so that we know that this tag is complete
return $this;
}
function __toString() {
$tag = $this->t_counter + 1;
$output = "<" . $this->tags[$tag];
foreach ($this->attrs[$tag] as $key => $value) {
$output .= " {$key}=\"" . htmlspecialchars($value) . "\"";
}
$output .= ">";
$output .= $this->text[$tag];
$output .= "</" . $this->tags[$tag] . ">";
unset($this->tags[$tag]);
unset($this->attrs[$tag]);
unset($this->text[$tag]);
$this->t_counter = $tag;
return $output;
}
}