Last active
July 5, 2019 11:07
-
-
Save caramelchocolate/e702f007bb51d35aca23a3f99247a591 to your computer and use it in GitHub Desktop.
PHP Closure
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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