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?
>> 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With