[英]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. 我想在匿名函数中使用
self
访问类常量。
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 ...
致命错误:当没有类活动在...时,无法访问self ::
Is it possible to pass the parent class into the scope of this anonymous function? 是否可以将父类传递到此匿名函数的范围内? Would a
use
statement work? use
声明是否有效?
>> All versions test of PHP 5.4+ way on 3v4l << >>所有版本测试PHP 5.4+在3v4l上的方式<<
PHP 5.4+ WAY: PHP 5.4+方式:
This has become significantly simpler since PHP 5.4, where $this
is no longer dirty: 自PHP 5.4以来,这变得非常简单,其中
$this
不再是脏的:
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: 前5.4方式:
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. 不幸的是你不能
use ($this)
YET。 They're working on it. 他们正在努力。 I expect it to work in PHP >= 5.4.
我希望它能在PHP> = 5.4下工作。
afaik anonymous functions are just that.. functions. afaik匿名函数只是..函数。 Not class methods, so scope is out.
不是类方法,因此范围不大。 You can pass the constant as an argument or use My_Class::CLASS_CONSTANT.
您可以将常量作为参数传递或使用My_Class :: CLASS_CONSTANT。
You're accessing the self inside an anonymous function, this won't work. 你在匿名函数中访问自己,这是行不通的。 What you should do is use
My_Class::CLASS_CONSTANT
instead of the self reference. 你应该做的是使用
My_Class::CLASS_CONSTANT
而不是自引用。
No, that's not possible. 不,那是不可能的。 Similarly, you can not bind $this to an anonymous function.
同样,您不能将$ this绑定到匿名函数。 Just passing the necessary values instead should do the trick though?
只是传递必要的值,但应该做的伎俩呢?
<?php
class My_Class {
const CLASS_CONSTANT = 'test value';
private function my_function(){
$lambda = function( $yourConstant ){
return $yourConstant;
};
return $lambda( self::CLASS_CONSTANT );
}
public function test( ) {
return $this->my_function( );
}
}
$class = new My_Class( );
echo $class->test( ); // 'test value'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.