Accessing private variables from within a closure

前端 未结 3 1107
天涯浪人
天涯浪人 2020-12-18 23:22

I\'m trying to reference a private variable of an object from within a closure. The code below would seem to work, but it complains Fatal error: Cannot access self:: w

3条回答
  •  生来不讨喜
    2020-12-18 23:57

    This is possible starting in PHP 5.4.0

    class test {
        function testMe() {
            $test = new test;
            $func = function() use ($test) {
                $test->findMe();        // Can see protected method
                $test::findMeStatically();  // Can see static protected method
            };
            $func();
            return $func;
        }
    
        protected function findMe() {
            echo " [find Me] \n";
        }
    
        protected static function findMeStatically() {
            echo " [find Me Statically] \n";
        }
    }
    
    $test = new test;
    $func = $test->testMe();
    $func();        // Can call from another context as long as 
                // the closure was created in the proper context.
    

提交回复
热议问题