简体   繁体   中英

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();

I want to bind self::closure() to self::$closure , and use it internal, but it disappears somewhere. How do I bind a closure to a static class variable in PHP?

  • Change your property to be static static $closure;
  • Wrap your callable in brackets (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();

There are 2 problems:

Missing static :

public static $closure;

Missing parentheses:

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM