Last active
December 16, 2015 02:54
-
-
Save Petah/47f9b8429b29857d869f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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