Search code examples
phpstaticclosuresbind

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?


Solution

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