3v4l.org

run code in 300+ PHP versions simultaneously
<?php interface BehaviorInterface {} abstract class BaseService { protected $behaviors; public function addBehavior(BehaviorInterface $b, array $export = []) { if (!count($this->behaviors)) { $this->behaviors[] = ['object' => $b, 'export' => $export]; return $this; } foreach ($this->behaviors as $behavior) { if (count($export) && count(array_intersect($behavior['export'], $export)) > 0) { throw new \Exception("Some of export methods already exists"); } $this->behaviors[] = ['object' => $b, 'export' => $export]; } return $this; } public function __call($name, $arguments) { foreach ($this->behaviors as $behavior) { if ((in_array($name, $behavior['export']) || !count($behavior['export'])) && method_exists($behavior['object'], $name)) { return call_user_func_array([$behavior['object'], $name], $arguments); } } $class = get_called_class(); throw new \Exception('Method "' . $name . '" does not exist in class "' . $class . '"'); } } class SayHui implements BehaviorInterface { public function hui($name) { echo $name, ', hui tebe!' . PHP_EOL; } } class NewSayHui implements BehaviorInterface { public function hui($name) { echo 'Fuck you, ' . $name . '!' . PHP_EOL; } } class HuiService extends BaseService { } class HuiService2 extends BaseService { } class HuiService3 extends BaseService { } $huiService = new HuiService(); $huiService->addBehavior(new SayHui(), ['hui']) ->hui('Nikita'); $huiService = new HuiService2(); $huiService->addBehavior(new NewSayHui(), ['hui']) ->hui('Eugene'); $huiService = new HuiService3(); $huiService->addBehavior(new SayHui()) ->addBehavior(new NewSayHui()) ->hui('Shandor');

preferences:
56.27 ms | 402 KiB | 5 Q