Skip to content

Instantly share code, notes, and snippets.

@mblarsen
Last active July 24, 2016 03:23
Show Gist options
  • Save mblarsen/f06e5bb61721b0efe9619ac54a745c6b to your computer and use it in GitHub Desktop.
Save mblarsen/f06e5bb61721b0efe9619ac54a745c6b to your computer and use it in GitHub Desktop.
Closure::bind (native JS-like bind in PHP)
<?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;
@mblarsen
Copy link
Author

There is a non-static version called Closure::bindTo()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment