Skip to content

Instantly share code, notes, and snippets.

@Petah
Last active December 16, 2015 02:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Petah/47f9b8429b29857d869f to your computer and use it in GitHub Desktop.
Save Petah/47f9b8429b29857d869f to your computer and use it in GitHub Desktop.
<?php
class Tag {
private $name;
private $attributes = [];
private $content = [];
public function __construct($name) {
$this->name = $name;
}
public function attr($key, $value) {
$this->attributes[$key] = $value;
return $this;
}
public function append($content) {
$this->content[] = $content;
return $this;
}
public function __toString() {
$attributes = '';
foreach ($this->attributes as $key => $value) {
$attributes .= ' ' . $key . '="' . htmlspecialchars($value, ENT_QUOTES) . '"';
}
$result = "<{$this->name}{$attributes}>";
foreach ($this->content as $content) {
$result .= $content;
}
$result .= "</{$this->name}>";
return $result;
}
}
class Ul extends Tag {
public function __construct() {
parent::__construct('ul');
}
}
class Li extends Tag {
public function __construct() {
parent::__construct('li');
}
}
$ul = new Ul();
$ul->append((new Li())->append('List item 1')->attr('class', 'list-item'));
$ul->append((new Li())->append('List item 2')->attr('class', 'list-item'));
$ul->append((new Li())->append('List item 3')->attr('class', 'list-item'));
echo $ul;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment