9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHP7調査(29)Closure::call()の新設

Last updated at Posted at 2015-05-07

無名関数に対応するClosureクラスにcall()メソッドが増えました。これはJavaScriptのFunction.prototype.callに対応するようなメソッドで、次のように使えます。

<?php
class Foo { private $bar = 'baz'; }
(function () { var_dump($this->bar); })->call(new Foo()); // string(3) "baz"

なんと、クラス外の関数をあたかもインスタンスメソッドのように呼び出すことができています。

といっても、これはPHP 5.4で導入されたClosure::bindTo()でも実現できることです。

<?php
class Foo { private $bar = 'baz'; }
(function () { var_dump($this->bar); })->bindTo(new Foo(), 'Foo')(); // string(3) "baz"

とはいえClosure::call()の方が断然読みやすいので良いと思います。

参照

9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?