Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 787
CodeXP Avatar asked Feb 05 '14 20:02

CodeXP


1 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();
like image 158
FabioCosta Avatar answered Oct 25 '22 17:10

FabioCosta