3v4l.org

run code in 500+ PHP versions simultaneously
<?php namespace RefactoringGuru\Singleton\RealWorld; /** * Если вам необходимо поддерживать в приложении несколько типов Одиночек, вы * можете определить основные функции Одиночки в базовом классе, тогда как * фактическую бизнес-логику (например, ведение журнала) перенести в подклассы. */ class Singleton { /** * Реальный экземпляр одиночки почти всегда находится внутри статического * поля. В этом случае статическое поле является массивом, где каждый * подкласс Одиночки хранит свой собственный экземпляр. */ private static $instances = []; /** * Конструктор Одиночки не должен быть публичным. Однако он не может быть * приватным, если мы хотим разрешить создание подклассов. */ protected function __construct() { } /** * Клонирование и десериализация не разрешены для одиночек. */ protected function __clone() { } public function __wakeup() { throw new \Exception("Cannot unserialize singleton"); } /** * Метод, используемый для получения экземпляра Одиночки. */ public static function getInstance() { $subclass = static::class; if (!isset(self::$instances[$subclass])) { // Обратите внимание, что здесь мы используем ключевое слово // "static" вместо фактического имени класса. В этом контексте // ключевое слово "static" означает «имя текущего класса». Эта // особенность важна, потому что, когда метод вызывается в // подклассе, мы хотим, чтобы экземпляр этого подкласса был создан // здесь. self::$instances[$subclass] = new static(); } return self::$instances[$subclass]; } } /** * Класс ведения журнала является наиболее известным и похвальным использованием * паттерна Одиночка. */ class Logger extends Singleton { /** * Ресурс указателя файла файла журнала. */ private $fileHandle; /** * Поскольку конструктор Одиночки вызывается только один раз, постоянно * открыт всего лишь один файловый ресурс. * * Обратите внимание, что для простоты мы открываем здесь консольный поток * вместо фактического файла. */ protected function __construct() { $this->fileHandle = fopen('php://stdout', 'w'); } /** * Пишем запись в журнале в открытый файловый ресурс. */ public function writeLog(string $message): void { $date = date('Y-m-d'); fwrite($this->fileHandle, "$date: $message\n"); } /** * Просто удобный ярлык для уменьшения объёма кода, необходимого для * регистрации сообщений из клиентского кода. */ public static function log(string $message): void { $logger = static::getInstance(); $logger->writeLog($message); } } /** * Применение паттерна Одиночка в хранилище настроек – тоже обычная практика. * Часто требуется получить доступ к настройкам приложений из самых разных мест * программы. Одиночка предоставляет это удобство. */ class Config extends Singleton { private $hashmap = []; public function getValue(string $key): string { return $this->hashmap[$key]; } public function setValue(string $key, string $value): void { $this->hashmap[$key] = $value; } } /** * Клиентский код. */ Logger::log("Started!"); // Сравниваем значения одиночки-Логгера. $l1 = Logger::getInstance(); $l2 = Logger::getInstance(); if ($l1 === $l2) { Logger::log("Logger has a single instance."); } else { Logger::log("Loggers are different."); } // Проверяем, как одиночка-Конфигурация сохраняет данные... $config1 = Config::getInstance(); $login = "test_login"; $password = "test_password"; $config1->setValue("login", $login); $config1->setValue("password", $password); // ...и восстанавливает их. $config2 = Config::getInstance(); if ($login == $config2->getValue("login") && $password == $config2->getValue("password") ) { Logger::log("Config singleton also works fine."); } Logger::log("Finished!");
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 43) Position 1 = 11, Position 2 = 15
Branch analysis from position: 11
1 jumps found. (Code = 42) Position 1 = 18
Branch analysis from position: 18
2 jumps found. (Code = 46) Position 1 = 39, Position 2 = 44
Branch analysis from position: 39
2 jumps found. (Code = 43) Position 1 = 45, Position 2 = 48
Branch analysis from position: 45
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 48
Branch analysis from position: 44
Branch analysis from position: 15
2 jumps found. (Code = 46) Position 1 = 39, Position 2 = 44
Branch analysis from position: 39
Branch analysis from position: 44
filename:       /in/927RG
function name:  (null)
number of ops:  52
compiled vars:  !0 = $l1, !1 = $l2, !2 = $config1, !3 = $login, !4 = $password, !5 = $config2
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
  121     0  E >   INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CRealWorld%5CLogger', 'log'
          1        SEND_VAL                                                     'Started%21'
          2        DO_FCALL                                          0          
  124     3        INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CRealWorld%5CLogger', 'getInstance'
          4        DO_FCALL                                          0  $7      
          5        ASSIGN                                                       !0, $7
  125     6        INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CRealWorld%5CLogger', 'getInstance'
          7        DO_FCALL                                          0  $9      
          8        ASSIGN                                                       !1, $9
  126     9        IS_IDENTICAL                                                 !0, !1
         10      > JMPZ                                                         ~11, ->15
  127    11    >   INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CRealWorld%5CLogger', 'log'
         12        SEND_VAL                                                     'Logger+has+a+single+instance.'
         13        DO_FCALL                                          0          
  126    14      > JMP                                                          ->18
  129    15    >   INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CRealWorld%5CLogger', 'log'
         16        SEND_VAL                                                     'Loggers+are+different.'
         17        DO_FCALL                                          0          
  133    18    >   INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CRealWorld%5CConfig', 'getInstance'
         19        DO_FCALL                                          0  $14     
         20        ASSIGN                                                       !2, $14
  134    21        ASSIGN                                                       !3, 'test_login'
  135    22        ASSIGN                                                       !4, 'test_password'
  136    23        INIT_METHOD_CALL                                             !2, 'setValue'
         24        SEND_VAL_EX                                                  'login'
         25        SEND_VAR_EX                                                  !3
         26        DO_FCALL                                          0          
  137    27        INIT_METHOD_CALL                                             !2, 'setValue'
         28        SEND_VAL_EX                                                  'password'
         29        SEND_VAR_EX                                                  !4
         30        DO_FCALL                                          0          
  139    31        INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CRealWorld%5CConfig', 'getInstance'
         32        DO_FCALL                                          0  $20     
         33        ASSIGN                                                       !5, $20
  140    34        INIT_METHOD_CALL                                             !5, 'getValue'
         35        SEND_VAL_EX                                                  'login'
         36        DO_FCALL                                          0  $22     
         37        IS_EQUAL                                             ~23     !3, $22
         38      > JMPZ_EX                                              ~23     ~23, ->44
  141    39    >   INIT_METHOD_CALL                                             !5, 'getValue'
         40        SEND_VAL_EX                                                  'password'
         41        DO_FCALL                                          0  $24     
         42        IS_EQUAL                                             ~25     !4, $24
         43        BOOL                                                 ~23     ~25
         44    > > JMPZ                                                         ~23, ->48
  143    45    >   INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CRealWorld%5CLogger', 'log'
         46        SEND_VAL                                                     'Config+singleton+also+works+fine.'
         47        DO_FCALL                                          0          
  146    48    >   INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CRealWorld%5CLogger', 'log'
         49        SEND_VAL                                                     'Finished%21'
         50        DO_FCALL                                          0          
         51      > RETURN                                                       1

Class RefactoringGuru\Singleton\RealWorld\Singleton:
Function __construct:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/927RG
function name:  __construct
number of ops:  1
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   23     0  E > > RETURN                                                       null

End of function __construct

Function __clone:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/927RG
function name:  __clone
number of ops:  1
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   28     0  E > > RETURN                                                       null

End of function __clone

Function __wakeup:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 108) Position 1 = -2
filename:       /in/927RG
function name:  __wakeup
number of ops:  5
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   32     0  E >   NEW                                                  $0      'Exception'
          1        SEND_VAL_EX                                                  'Cannot+unserialize+singleton'
          2        DO_FCALL                                          0          
          3      > THROW                                             0          $0
   33     4*     > RETURN                                                       null

End of function __wakeup

Function getinstance:
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 43) Position 1 = 6, Position 2 = 11
Branch analysis from position: 6
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 11
filename:       /in/927RG
function name:  getInstance
number of ops:  15
compiled vars:  !0 = $subclass
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   40     0  E >   FETCH_CLASS_NAME                                     ~1      
          1        ASSIGN                                                       !0, ~1
   41     2        FETCH_STATIC_PROP_IS                                 ~3      'instances'
          3        ISSET_ISEMPTY_DIM_OBJ                             0  ~4      ~3, !0
          4        BOOL_NOT                                             ~5      ~4
          5      > JMPZ                                                         ~5, ->11
   49     6    >   NEW                              static              $8      
          7        DO_FCALL                                          0          
          8        FETCH_STATIC_PROP_W              unknown             $6      'instances'
          9        ASSIGN_DIM                                                   $6, !0
         10        OP_DATA                                                      $8
   51    11    >   FETCH_STATIC_PROP_R              unknown             ~10     'instances'
         12        FETCH_DIM_R                                          ~11     ~10, !0
         13      > RETURN                                                       ~11
   52    14*     > RETURN                                                       null

End of function getinstance

End of class RefactoringGuru\Singleton\RealWorld\Singleton.

Class RefactoringGuru\Singleton\RealWorld\Logger:
Function __construct:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/927RG
function name:  __construct
number of ops:  7
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   75     0  E >   INIT_NS_FCALL_BY_NAME                                        'RefactoringGuru%5CSingleton%5CRealWorld%5Cfopen'
          1        SEND_VAL_EX                                                  'php%3A%2F%2Fstdout'
          2        SEND_VAL_EX                                                  'w'
          3        DO_FCALL                                          0  $1      
          4        ASSIGN_OBJ                                                   'fileHandle'
          5        OP_DATA                                                      $1
   76     6      > RETURN                                                       null

End of function __construct

Function writelog:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/927RG
function name:  writeLog
number of ops:  16
compiled vars:  !0 = $message, !1 = $date
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   81     0  E >   RECV                                                 !0      
   83     1        INIT_NS_FCALL_BY_NAME                                        'RefactoringGuru%5CSingleton%5CRealWorld%5Cdate'
          2        SEND_VAL_EX                                                  'Y-m-d'
          3        DO_FCALL                                          0  $2      
          4        ASSIGN                                                       !1, $2
   84     5        INIT_NS_FCALL_BY_NAME                                        'RefactoringGuru%5CSingleton%5CRealWorld%5Cfwrite'
          6        CHECK_FUNC_ARG                                               
          7        FETCH_OBJ_FUNC_ARG                                   $4      'fileHandle'
          8        SEND_FUNC_ARG                                                $4
          9        ROPE_INIT                                         4  ~6      !1
         10        ROPE_ADD                                          1  ~6      ~6, '%3A+'
         11        ROPE_ADD                                          2  ~6      ~6, !0
         12        ROPE_END                                          3  ~5      ~6, '%0A'
         13        SEND_VAL_EX                                                  ~5
         14        DO_FCALL                                          0          
   85    15      > RETURN                                                       null

End of function writelog

Function log:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/927RG
function name:  log
number of ops:  8
compiled vars:  !0 = $message, !1 = $logger
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   91     0  E >   RECV                                                 !0      
   93     1        INIT_STATIC_METHOD_CALL                                      'getInstance'
          2        DO_FCALL                                          0  $2      
          3        ASSIGN                                                       !1, $2
   94     4        INIT_METHOD_CALL                                             !1, 'writeLog'
          5        SEND_VAR_EX                                                  !0
          6        DO_FCALL                                          0          
   95     7      > RETURN                                                       null

End of function log

Function __clone:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/927RG
function name:  __clone
number of ops:  1
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   28     0  E > > RETURN                                                       null

End of function __clone

Function __wakeup:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 108) Position 1 = -2
filename:       /in/927RG
function name:  __wakeup
number of ops:  5
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   32     0  E >   NEW                                                  $0      'Exception'
          1        SEND_VAL_EX                                                  'Cannot+unserialize+singleton'
          2        DO_FCALL                                          0          
          3      > THROW                                             0          $0
   33     4*     > RETURN                                                       null

End of function __wakeup

Function getinstance:
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 43) Position 1 = 6, Position 2 = 11
Branch analysis from position: 6
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 11
filename:       /in/927RG
function name:  getInstance
number of ops:  15
compiled vars:  !0 = $subclass
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   40     0  E >   FETCH_CLASS_NAME                                     ~1      
          1        ASSIGN                                                       !0, ~1
   41     2        FETCH_STATIC_PROP_IS                                 ~3      'instances'
          3        ISSET_ISEMPTY_DIM_OBJ                             0  ~4      ~3, !0
          4        BOOL_NOT                                             ~5      ~4
          5      > JMPZ                                                         ~5, ->11
   49     6    >   NEW                              static              $8      
          7        DO_FCALL                                          0          
          8        FETCH_STATIC_PROP_W              unknown             $6      'instances'
          9        ASSIGN_DIM                                                   $6, !0
         10        OP_DATA                                                      $8
   51    11    >   FETCH_STATIC_PROP_R              unknown             ~10     'instances'
         12        FETCH_DIM_R                                          ~11     ~10, !0
         13      > RETURN                                                       ~11
   52    14*     > RETURN                                                       null

End of function getinstance

End of class RefactoringGuru\Singleton\RealWorld\Logger.

Class RefactoringGuru\Singleton\RealWorld\Config:
Function getvalue:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/927RG
function name:  getValue
number of ops:  7
compiled vars:  !0 = $key
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
  107     0  E >   RECV                                                 !0      
  109     1        FETCH_OBJ_R                                          ~1      'hashmap'
          2        FETCH_DIM_R                                          ~2      ~1, !0
          3        VERIFY_RETURN_TYPE                                           ~2
          4      > RETURN                                                       ~2
  110     5*       VERIFY_RETURN_TYPE                                           
          6*     > RETURN                                                       null

End of function getvalue

Function setvalue:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/927RG
function name:  setValue
number of ops:  6
compiled vars:  !0 = $key, !1 = $value
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
  112     0  E >   RECV                                                 !0      
          1        RECV                                                 !1      
  114     2        FETCH_OBJ_W                                          $2      'hashmap'
          3        ASSIGN_DIM                                                   $2, !0
          4        OP_DATA                                                      !1
  115     5      > RETURN                                                       null

End of function setvalue

Function __construct:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/927RG
function name:  __construct
number of ops:  1
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   23     0  E > > RETURN                                                       null

End of function __construct

Function __clone:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/927RG
function name:  __clone
number of ops:  1
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   28     0  E > > RETURN                                                       null

End of function __clone

Function __wakeup:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 108) Position 1 = -2
filename:       /in/927RG
function name:  __wakeup
number of ops:  5
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   32     0  E >   NEW                                                  $0      'Exception'
          1        SEND_VAL_EX                                                  'Cannot+unserialize+singleton'
          2        DO_FCALL                                          0          
          3      > THROW                                             0          $0
   33     4*     > RETURN                                                       null

End of function __wakeup

Function getinstance:
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 43) Position 1 = 6, Position 2 = 11
Branch analysis from position: 6
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 11
filename:       /in/927RG
function name:  getInstance
number of ops:  15
compiled vars:  !0 = $subclass
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   40     0  E >   FETCH_CLASS_NAME                                     ~1      
          1        ASSIGN                                                       !0, ~1
   41     2        FETCH_STATIC_PROP_IS                                 ~3      'instances'
          3        ISSET_ISEMPTY_DIM_OBJ                             0  ~4      ~3, !0
          4        BOOL_NOT                                             ~5      ~4
          5      > JMPZ                                                         ~5, ->11
   49     6    >   NEW                              static              $8      
          7        DO_FCALL                                          0          
          8        FETCH_STATIC_PROP_W              unknown             $6      'instances'
          9        ASSIGN_DIM                                                   $6, !0
         10        OP_DATA                                                      $8
   51    11    >   FETCH_STATIC_PROP_R              unknown             ~10     'instances'
         12        FETCH_DIM_R                                          ~11     ~10, !0
         13      > RETURN                                                       ~11
   52    14*     > RETURN                                                       null

End of function getinstance

End of class RefactoringGuru\Singleton\RealWorld\Config.

Generated using Vulcan Logic Dumper, using php 8.5.0


preferences:
162.88 ms | 2033 KiB | 16 Q