Accessing private variables from within a closure

前端 未结 3 1101
天涯浪人
天涯浪人 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-19 00:16

    Edit to note, this answer was originally meant for PHP5.3 and earlier, it's possible now. For current information, see this answer.


    This is not directly possible. In particularly, closures have no associated scope, so they cannot access private and protected members.

    You can, however, use references:

    _var2;
            $closure = function () use ( $value, &$field ) {
                $field = $value;
            };
            $closure();
        }
    
    }
    
    MyClass::setVar1( "hello" );
    
    $myclass = new MyClass;
    $myclass->setVar2( "hello" );
    

提交回复
热议问题