3v4l.org

run code in 500+ PHP versions simultaneously
<?php namespace RefactoringGuru\Singleton\Conceptual; /** * Класс Одиночка предоставляет метод `GetInstance`, который ведёт себя как * альтернативный конструктор и позволяет клиентам получать один и тот же * экземпляр класса при каждом вызове. */ class Singleton { /** * Объект одиночки храниться в статичном поле класса. Это поле — массив, так * как мы позволим нашему Одиночке иметь подклассы. Все элементы этого * массива будут экземплярами кокретных подклассов Одиночки. Не волнуйтесь, * мы вот-вот познакомимся с тем, как это работает. */ private static $instances = []; /** * Конструктор Одиночки всегда должен быть скрытым, чтобы предотвратить * создание объекта через оператор new. */ protected function __construct() { } /** * Одиночки не должны быть клонируемыми. */ protected function __clone() { } /** * Одиночки не должны быть восстанавливаемыми из строк. */ public function __wakeup() { throw new \Exception("Cannot unserialize a singleton."); } /** * Это статический метод, управляющий доступом к экземпляру одиночки. При * первом запуске, он создаёт экземпляр одиночки и помещает его в * статическое поле. При последующих запусках, он возвращает клиенту объект, * хранящийся в статическом поле. * * Эта реализация позволяет вам расширять класс Одиночки, сохраняя повсюду * только один экземпляр каждого подкласса. */ public static function getInstance(): Singleton { $cls = static::class; if (!isset(self::$instances[$cls])) { self::$instances[$cls] = new static(); } return self::$instances[$cls]; } /** * Наконец, любой одиночка должен содержать некоторую бизнес-логику, которая * может быть выполнена на его экземпляре. */ public function someBusinessLogic() { // ... } } /** * Клиентский код. */ function clientCode() { $s1 = Singleton::getInstance(); $s2 = Singleton::getInstance(); if ($s1 === $s2) { echo "Singleton works, both variables contain the same instance."; } else { echo "Singleton failed, variables contain different instances."; } } clientCode();
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/gULrv
function name:  (null)
number of ops:  3
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   82     0  E >   INIT_NS_FCALL_BY_NAME                                        'RefactoringGuru%5CSingleton%5CConceptual%5CclientCode'
          1        DO_FCALL                                          0          
          2      > RETURN                                                       1

Function refactoringguru%5Csingleton%5Cconceptual%5Cclientcode:
Finding entry points
Branch analysis from position: 0
2 jumps found. (Code = 43) Position 1 = 8, Position 2 = 10
Branch analysis from position: 8
1 jumps found. (Code = 42) Position 1 = 11
Branch analysis from position: 11
1 jumps found. (Code = 62) Position 1 = -2
Branch analysis from position: 10
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/gULrv
function name:  RefactoringGuru\Singleton\Conceptual\clientCode
number of ops:  12
compiled vars:  !0 = $s1, !1 = $s2
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   73     0  E >   INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CConceptual%5CSingleton', 'getInstance'
          1        DO_FCALL                                          0  $2      
          2        ASSIGN                                                       !0, $2
   74     3        INIT_STATIC_METHOD_CALL                                      'RefactoringGuru%5CSingleton%5CConceptual%5CSingleton', 'getInstance'
          4        DO_FCALL                                          0  $4      
          5        ASSIGN                                                       !1, $4
   75     6        IS_IDENTICAL                                                 !0, !1
          7      > JMPZ                                                         ~6, ->10
   76     8    >   ECHO                                                         'Singleton+works%2C+both+variables+contain+the+same+instance.'
   75     9      > JMP                                                          ->11
   78    10    >   ECHO                                                         'Singleton+failed%2C+variables+contain+different+instances.'
   80    11    > > RETURN                                                       null

End of function refactoringguru%5Csingleton%5Cconceptual%5Cclientcode

Class RefactoringGuru\Singleton\Conceptual\Singleton:
Function __construct:
Finding entry points
Branch analysis from position: 0
1 jumps found. (Code = 62) Position 1 = -2
filename:       /in/gULrv
function name:  __construct
number of ops:  1
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   24     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/gULrv
function name:  __clone
number of ops:  1
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   29     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/gULrv
function name:  __wakeup
number of ops:  5
compiled vars:  none
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   36     0  E >   NEW                                                  $0      'Exception'
          1        SEND_VAL_EX                                                  'Cannot+unserialize+a+singleton.'
          2        DO_FCALL                                          0          
          3      > THROW                                             0          $0
   37     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/gULrv
function name:  getInstance
number of ops:  17
compiled vars:  !0 = $cls
line      #* E I O op                               fetch          ext  return  operands
-----------------------------------------------------------------------------------------
   50     0  E >   FETCH_CLASS_NAME                                     ~1      
          1        ASSIGN                                                       !0, ~1
   51     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
   52     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
   55    11    >   FETCH_STATIC_PROP_R              unknown             ~10     'instances'
         12        FETCH_DIM_R                                          ~11     ~10, !0
         13        VERIFY_RETURN_TYPE                                           ~11
         14      > RETURN                                                       ~11
   56    15*       VERIFY_RETURN_TYPE                                           
         16*     > RETURN                                                       null

End of function getinstance

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

End of function somebusinesslogic

End of class RefactoringGuru\Singleton\Conceptual\Singleton.

Generated using Vulcan Logic Dumper, using php 8.5.0


preferences:
171.9 ms | 2010 KiB | 14 Q