Created
January 13, 2012 17:29
-
-
Save dshafik/1607647 to your computer and use it in GitHub Desktop.
The Closure Puzzle
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 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(); |
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 Foo { | |
public function A() | |
{ | |
$closure = function () { | |
$this->B(); | |
}; | |
$closure(); // Foo::B | |
} | |
public function B() | |
{ | |
echo __METHOD__, PHP_EOL; | |
} | |
} |
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 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