Skip to content

Instantly share code, notes, and snippets.

@caramelchocolate
Last active July 5, 2019 11:07
Show Gist options
  • Save caramelchocolate/e702f007bb51d35aca23a3f99247a591 to your computer and use it in GitHub Desktop.
Save caramelchocolate/e702f007bb51d35aca23a3f99247a591 to your computer and use it in GitHub Desktop.
PHP Closure
<?php
class a {
protected $hoge = 'foo';
}
$a = new a();
$closure = Closure::bind(function () {
$this->hoge = 'foofoo';
}, $a, $a);
$closure();
$closure = Closure::bind(function () {
echo $this->hoge . PHP_EOL;
}, $a, $a);
$closure(); //-> foofoo
?>
<?php
class a {
protected $hoge = 'foo';
public function bind (Closure $closure, $closure_args=[]) {
$ret = false;
if (is_callable($closure)) {
$closure = Closure::bind($closure, $this, $this);
$ret = call_user_func_array($closure, $closure_args);
}
return $ret;
}
}
$a = new a();
echo $a->bind(function ($field) {
return $this->$field;
}, ['hoge']); //<- foo
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment