Last active
May 12, 2017 05:35
-
-
Save msyk/6f7d79e5b98a2dbc4ab0d30fc7cf05db 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 | |
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