Last active
July 24, 2016 03:23
-
-
Save mblarsen/f06e5bb61721b0efe9619ac54a745c6b to your computer and use it in GitHub Desktop.
Closure::bind (native JS-like bind in PHP)
This file contains 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 { | |
public $param = 7; | |
} | |
class B { | |
private $param = 28; | |
} | |
class C { | |
public function __get($key) | |
{ | |
if ($key === 'param') { | |
return '42'; | |
} | |
return 'Huh?'; | |
} | |
} | |
// An anoymous function using `$this` | |
$closure = function () { return $this->param; }; | |
// Bind to an instance of A. Since param on A is public we don't | |
// need to change the scope | |
$aClosure = Closure::bind($closure, new A); | |
echo $aClosure() . PHP_EOL; | |
// Same as above but param on B is private so we need to change | |
// the scope to 'B' | |
$aClosure = Closure::bind($closure, new B, 'B'); | |
echo $aClosure(). PHP_EOL; | |
// Save as A but with __get magic method | |
$aClosure = Closure::bind($closure, new C); | |
echo $aClosure(). PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There is a non-static version called
Closure::bindTo()