Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access class constants using `self::` inside an anonymous function defined in a method?

I would like to access a class constant using self from within an anonymous function.

class My_Class {    
    const  CLASS_CONSTANT = 'test value';
    private function my_function(){     
        $lambda_function = function(){
            echo self::CLASS_CONSTANT;
        };
        $lambda_function();
    }
}

When I tried this, I get the error:

Fatal error: Cannot access self:: when no class scope is active in ...

Is it possible to pass the parent class into the scope of this anonymous function? Would a use statement work?

like image 814
steampowered Avatar asked Nov 23 '11 14:11

steampowered


1 Answers

>> All versions test of PHP 5.4+ way on 3v4l <<

PHP 5.4+ WAY:

This has become significantly simpler since PHP 5.4, where $this is no longer dirty:

class My_Class {
    const CLASS_CONSTANT = 'test value';

    private function my_function() {
        $lambda_function = function() {
            // $this is actually inherited from the parent object, so
            // you don't even need a use() statement
            echo $this::CLASS_CONSTANT;

            // Or just use self, that's inherited too
            echo self::CLASS_CONSTANT;
        };
        $lambda_function();
    }
}

PRE 5.4 WAY:

Make the anonymous function a closure -- by introducing scoped variables into the function -- and call the constant from that:

class My_Class {
    const CLASS_CONSTANT = 'test value';
    private function my_function() {
        $self = $this;
        $lambda_function = function() use ($self) { // now it's a closure
            echo $self::CLASS_CONSTANT;
        } // << you forgot a ;
        lambda_function(); // << you forgot a $
    }
}

Unfortunately you can't use ($this) YET. They're working on it. I expect it to work in PHP >= 5.4.

like image 142
Rudie Avatar answered Sep 22 '22 04:09

Rudie