이장희*_*이장희 3 php static closures bind
<?php
class A
{
public $closure;
public static function myFunc($input): string
{
$output = $input . ' is Number';
return $output;
}
public static function closure(): Closure
{
return function ($input) {
return self::myFunc($input);
};
}
public static function run()
{
$closure = self::closure();
echo $closure(1); // 1 is Number
self::$closure = $closure;
echo self::$closure(2); // Fatal error
}
}
A::run();
Run Code Online (Sandbox Code Playgroud)
我想绑定self::closure()到self::$closure,并在内部使用它,但是它消失在某个地方。如何在PHP中将闭包绑定到静态类变量?
static $closure;(self::$closure)(2);http://sandbox.onlinephpfunctions.com/code/d41490759cac39b8459e396b3acf99bf22c65a68
<?php
class A
{
static $closure;
public static function myFunc($input): string
{
$output = $input . ' is Number';
return $output;
}
public static function closure(): Closure
{
return function ($input) {
return self::myFunc($input);
};
}
public static function run()
{
$closure = self::closure();
echo $closure(1); // 1 is Number
self::$closure = $closure;
// Wrap your callable in brackets
echo (self::$closure)(2);
}
}
A::run();
Run Code Online (Sandbox Code Playgroud)