LoginSignup
7
4

More than 5 years have passed since last update.

PHPのクロージャで $this を使う方法

Posted at

$this はそのまま use で渡せないので、 $that = $this; みたいなことをする。どっかのスクリプト言語で見たような・・・。

<?php

class Foo
{
    public function getClosure()
    {
        $that = $this;

        $closure = function() use ($that) {
            $that->bar();
        };

        return $closure;
    }

    public function bar()
    {
        echo 'Called bar method.', PHP_EOL;
    }
}

$foo = new Foo();
$closure = $foo->getClosure();
$closure(); // Called bar method.
7
4
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
7
4