<?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();
我想将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();
有两个问题:
缺少static
:
publicstatic$closure;
缺少括号:
echo(self::$closure)(2);
<?php
class A
{
public 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;
echo (self::$closure)(2); // 2 is Number
}
}
A::run();