如何将闭包绑定到 PHP 中的静态 class 变量?

How do I bind a closure to a static class variable in PHP?

<?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 中的静态 class 变量?

有2个问题:

缺少static

public <strong>static</strong> $closure;

缺少括号:

echo <b>(</b>self::$closure<b>)</b>(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();
  • 将您的 属性 更改为静态 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();