Home » Php » php – How do I bind a closure created inside a static function to an instance

php – How do I bind a closure created inside a static function to an instance

Posted by: admin July 12, 2020 Leave a comment

Questions:

this seem not to work and I don’t know why?
you can create static closures inside non static methods, why not vice versa?

class RegularClass {
    private $name = 'REGULAR';
}

class StaticFunctions {
    public static function doStuff()
    {
        $func = function ()
        {
            // this is a static function unfortunately
            // try to access properties of bound instance
            echo $this->name;
        };

        $rc = new RegularClass();

        $bfunc = Closure::bind($func, $rc, 'RegularClass');

        $bfunc();
    }
}

StaticFunctions::doStuff();

// PHP Warning:  Cannot bind an instance to a static closure in /home/codexp/test.php on line 19
// PHP Fatal error:  Using $this when not in object context in /home/codexp/test.php on line 14
How to&Answers:

As i said on my comment it seems that you can’t change the “$this” from a closure that comes from a static context.
“Static closures cannot have any bound object (the value of the parameter newthis should be NULL), but this function can nevertheless be used to change their class scope.”
I guess you will have to make something like this:

    class RegularClass {
        private $name = 'REGULAR';
    }

    class Holder{
        public function getFunc(){
            $func = function ()
            {
                // this is a static function unfortunately
                // try to access properties of bound instance
                echo $this->name;
            };
            return $func;
        }
    }
    class StaticFunctions {
        public static function doStuff()
        {


            $rc = new RegularClass();
            $h=new Holder();
            $bfunc = Closure::bind($h->getFunc(), $rc, 'RegularClass');

            $bfunc();
        }
    }

    StaticFunctions::doStuff();