LoginSignup
5
5

More than 5 years have passed since last update.

PHPの Closure で bind 済みかどうか調べる

Posted at

PHPの Closure::bind 機能。
なんらかのクラスをバインドすれば、関数内でそのクラスを $this として使える。

けど、「そのClosureがすでにbind済みかどうか」を知る方法が標準では無さそう。
でも知りたい。

バインドしたのとしてないのとを比べ、ReflectionClassとかいろいろ試したけど違いが発見できなかった。
試しに var_dump すると、違いが出た。

// バインドしてないクロージャ
object(Closure)#2 (0) {
}

// バインドしたクロージャ
object(Closure)#3 (1) {
  ["this"]=>
  object(className)#1 (1) {
    ["className"]=>
    string(1) "className"
  }
}

もうこれを文字列として見るしかない!

バインドされたクラス名を取得する関数
function get_bind(Closure $closure)
{
    ob_start();
    var_dump($closure);
    $dump = ob_get_clean();
    if (preg_match('/\A[^\n]+[\n\s]+\["this"\][^\(]*?\(([^\)]+)\)/s', $dump, $m)) {
        return $m[1];
    }
    return false;
}

ということで泥くさい関数のできあがり・・・

5
5
2

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
5
5