简体   繁体   中英

PHP - self, static or $this in callback function

Is it possible to access classes/objects reffered as self , static and $this in anonymous callbacks in PHP? Just like this:

class Foo {
    const BAZ = 5;
    public static function bar() {
         echo self::BAZ; // it works OK
         array_filter(array(1,3,5), function($number) /* use(self) */ {
             return $number !== self::BAZ; // I cannot access self from here
         });
    }
}

Is there any way to make it behave as with usual variables, using use(self) clause?

With PHP5.4 it will be. For now it's not possible. However, if you only need access to public properties, method

$that = $this;
function () use ($that) { echo $that->doSomething(); }

For constants there is no reason to not use the qualified name

function () { echo Classname::FOO; }

Just use the standard way:

Foo::BAZ;

or

$baz = self::BAZ;
... function($number) use($baz) {
   $baz;
}

What about this:

class Foo {
    const BAZ = 5;
    $self = __class__;
    public static function bar() {
         echo self::BAZ; // it works OK
         array_filter(array(1,3,5), function($number) use($self) {
             return $number !== $self::BAZ; // access to self, just your const must be public
         });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM