Skip to content

Instantly share code, notes, and snippets.

@dshafik
Created January 13, 2012 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dshafik/1607647 to your computer and use it in GitHub Desktop.
Save dshafik/1607647 to your computer and use it in GitHub Desktop.
The Closure Puzzle
<?php
class Bar {
public function A()
{
echo __METHOD__, PHP_EOL;
}
private function B()
{
echo __METHOD__, PHP_EOL;
}
}
class Bat {
public function __call($function, $args)
{
$bar = new Bar();
if (is_callable(array($bar, $function))) {
$bar->{$function}();
} else {
$closure = function() use ($function, $bar) {
$bar->{$function}();
$this->C();
$this->D();
};
$bustOO = Closure::bind($closure, $this, $bar);
$bustOO();
}
}
public function C()
{
echo __METHOD__, PHP_EOL;
}
private function D()
{
echo __METHOD__, PHP_EOL;
}
}
$bat = new Bat();
$bat->A();
$bat->B();
<?php
class Foo {
public function A()
{
$closure = function () {
$this->B();
};
$closure(); // Foo::B
}
public function B()
{
echo __METHOD__, PHP_EOL;
}
}
$ php closure-puzzle.php
Bar::A
Bar::B
Bat::C
Fatal error: Call to undefined method Bar::D()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment