Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

php - Accessing private variables from within a closure

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:: when no class scope is active in test.php on line 12 and Fatal error: Using $this when not in object context in test.php on line 20.

Any ideas how to accomplish the same results using a closure while keeping the variables private and without making helper functions (defeating the whole idea of a private variable).

class MyClass
{

    static private $_var1;
    private $_var2;

    static function setVar1( $value )
    {
        $closure = function () use ( $value ) {
            self::$_var1 = $value;
        };
        $closure();
    }

    function setVar2( $value )
    {
        $closure = function () use ( $value ) {
            $this->_var2 = $value;
        };
        $closure();
    }

}

MyClass::setVar1( "hello" ); //doesn't work

$myclass = new MyClass;
$myclass->setVar2( "hello" ); //doesn't work
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

<?php
class MyClass
{

    static private $_var1;
    private $_var2;

    static function setVar1( $value )
    {
        $field =& self::$_var1;
        $closure = function () use ( $value,  &$field ) {
            $field = $value;
        };
        $closure();
    }

    function setVar2( $value )
    {
        $field =& $this->_var2;
        $closure = function () use ( $value, &$field ) {
            $field = $value;
        };
        $closure();
    }

}

MyClass::setVar1( "hello" );

$myclass = new MyClass;
$myclass->setVar2( "hello" );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...