3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?php define("TYPE", "CLI"); abstract class View { protected $imp; public function __construct() { if (TYPE == 'CLI') $this->imp = new ViewImplCli(); else if (TYPE == 'JSON') $this->imp = new ViewImplJson(); else throw new Exception('Unknown environment'); } public function addText($text) { return $this->imp->addText($text); } public function addLine() { return $this->imp->addLine(); } public function getResult() { print $this->imp->getResult(); } } class ViewContent extends View { public function printParagraph($text) { $this->addText($text); } } class ViewTable extends View { public function addCell($text) { $this->addLine(); $this->addText($text); $this->addLine(); } } abstract class ViewImpl { abstract public function addText($text); abstract public function addLine(); abstract public function getResult(); } class ViewImplCli extends ViewImpl { protected $result = ""; public function addLine() { $this->result .= str_repeat('-', 80).PHP_EOL; } public function addText($text) { $this->result .= $text.PHP_EOL; } public function getResult() { return $this->result; } } class ViewImplJson extends ViewImpl { protected $result = array(); public function addLine() { $this->result[] = array('type' => 'line'); } public function addText($text) { $this->result[] = array('type' => 'text', 'text' => $text); } public function getResult() { return json_encode($this->result); } } $content = new ViewContent(); $content->printParagraph('Hello world'); echo $content->getResult(); $table = new ViewTable(); $table->addCell('I am cell'); echo $table->getResult();
Output for 5.6.0 - 5.6.30, hhvm-3.15.4, 7.0.0 - 7.3.0beta1
Hello world -------------------------------------------------------------------------------- I am cell --------------------------------------------------------------------------------