Creating a static member of a class function (close) does not work

(PHP7) Consider the following code that tries to assign a function to a variable, and then make sure that it is called only once.

class a{
  static public $b;
  static public function init(){
     self::$b();
     self::$b=function(){};
  }
}
a::$b=function(){echo 'Here I do very heavy stuff, but will happen only in the first time I call init()';};

for($i=0;$i<1000;$i++){
   a::init();
}

In php7, an error will be issued according to which it a::$bwill be a string (the name of the function to call).
If I use pure variables and not static members, it will work.
My question is: is it possible or not, or is there a little tweak that I can do for this to work without pure vars ?

+4
source share
1 answer

PHP 7 :

(self::$b)();

PHP 5+ ( 7):

$init = self::$b;
$init();

3v4l.org.

+5

Source: https://habr.com/ru/post/1652896/


All Articles