3v4l.org

run code in 300+ PHP versions simultaneously
<?php class ServiceContainer { protected $services = []; public function get($id, callable $creator) { // Нет в кэше? Берём из creator'а. todo: Сделать защиту от цикличных зависимостей if (! isset($this->services[$id])) $this->services[$id] = $creator(); // Возвращаем кэш return $this->services[$id]; } public function set($id, $service) { $this->services[$id] = $service; } } class Framework { private static $services = null; public static function getServices() { if (is_null(static::$services)) { throw new \Exception('Не инициализировано'); } return static::$services; } public static function init(ServiceContainer $services = null) // Можно в качестве аргумента передать нужную реализацию ServiceContainer { if ( $services ) static::$services = $services; else static::$services = new ServiceContainer(); } public static function run() { // Маршрутизация => Контроллер => Выполнение Response } public static function getRouter() { return static::getServices()->get('framework.router', function() { return "router"; }); } } class CMS extends Framework { public static function run() { // Маршрутизация => Встроенные контроллеры/Модули => Выполнение Response } public static function getModulesManager() { return static::getServices()->get('cms.modulesmanager', function() { return "modulesManager"; }); } } // based on framework Framework::init() && Framework::run(); // где-то в компоненте: var_dump(Framework::getRouter()); // based on CMS CMS::init() && CMS::run(); // где-то в модуле: var_dump(CMS::getRouter()); var_dump(CMS::getModulesManager()); CMS::getServices()->set('framework.router', 'Ha, its not router!'); var_dump(CMS::getRouter());
Output for 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.6
string(6) "router" string(6) "router" string(14) "modulesManager" string(19) "Ha, its not router!"
Output for 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33
string(6) "router" Fatal error: Uncaught Error: Cannot access property CMS::$services in /in/nU8lt:41 Stack trace: #0 /in/nU8lt(78): Framework::init() #1 {main} thrown in /in/nU8lt on line 41
Process exited with code 255.
Output for 5.5.0 - 5.5.38, 5.6.0 - 5.6.40
string(6) "router" Fatal error: Cannot access property CMS::$services in /in/nU8lt on line 41
Process exited with code 255.

preferences:
227.6 ms | 402 KiB | 330 Q