Tom
Tom

Reputation: 612

Do not pass $this into scope of an anonymous function

Is there a way to not pass the class into an anonymous function?

class Foo{

  public function bar(){
     $data = [
        'calculation' => function(){
           // I don't want $this to be passed into here
        }
     ];
  }
}

Can i exclude $this from that anonymous function?

Upvotes: 1

Views: 44

Answers (1)

lonesomeday
lonesomeday

Reputation: 237845

If you don't want a value for $this, you want a static anonymous function.

class Foo{
  public function bar(){
     $data = [
        'calculation' => static function(){
           // $this is not defined
        }
     ];
  }
}

Static anonymous functions do not have a $this value automatically bound and they cannot have another value bound to them later on.

Upvotes: 2

Related Questions