Skip to content

Instantly share code, notes, and snippets.

@msyk
Last active May 12, 2017 05:35
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 msyk/6f7d79e5b98a2dbc4ab0d30fc7cf05db to your computer and use it in GitHub Desktop.
Save msyk/6f7d79e5b98a2dbc4ab0d30fc7cf05db to your computer and use it in GitHub Desktop.
<?php
abstract class Component {
protected $parent = null;
protected $children = array();
protected $name;
abstract function add($child);
abstract function remove($child);
abstract function getChildren();
abstract function print();
}
class Tag extends Component {
function __construct($name) {
$this->name = $name;
}
function add($child) {
$this->children[] = $child;
$child->parent = $this;
}
function remove($child) {
$counter = 0;
$exists = false;
foreach($this->children as $item) {
if($item===$child) {
$exists = true;
break;
}
$counter++;
}
if($exists) {
$this->children = array_splice($this->children, $counter, 1);
}
}
function getChildren() {
return $this->children;
}
function print() {
echo "<{$this->name}>";
foreach($this->children as $item) {
$item->print();
}
echo "</{$this->name}>";
}
}
$table = new Tag("table");
$tr = new Tag("tr");
$table->add($tr);
$td1 = new Tag("td");
$tr->add($td1);
$td2 = new Tag("td");
$tr->add($td2);
$table->print();
$tr->remove($td1);
$table->print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment