2018-02-27 21:53
浏览 289

在PHP 7匿名类中访问外部变量

PHP 7 added support for anonymous classes, however I can't seem to find any information regarding associated scoping issues. I know I can use the use keyword with callables/closures to access outer scoped variables (like function() use ($outer) { // do work with $outer }), is there any way to do that with an anonymous class?

I would like to be able to do so without relying on the anonymous class constructor arguments, and without doing things like adding a setter method or public property to store the value after the instantiation.

Here's an example:

$outer = 'something';

$instance = new class {
    public function testing() {
        var_dump($outer); // would like this to dump the string 'something'

图片转代码服务由CSDN问答提供 功能建议

PHP 7增加了对匿名类,但我似乎无法找到有关相关范围问题的任何信息。 我知道我可以使用带有callables / closures的 use 关键字来访问外部范围的变量(比如 function()use($ outer){//使用$ outer} ),有没有办法用匿名类做到这一点?

我希望能够这样做而不依赖于匿名类构造函数参数,并且无需添加 实例化后存储值的setter方法或公共属性。


  $ outer ='something'; \  n 
 $ instance = new class {
 public function testing(){
 var_dump($ outer);  //想要转储字符串'something'
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

3条回答 默认 最新

相关推荐 更多相似问题