public
Last active

The Closure Puzzle

  • Download Gist
closure-puzzle.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
<?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();
closure-this.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
<?php
class Foo {
public function A()
{
$closure = function () {
$this->B();
};
 
$closure(); // Foo::B
}
 
public function B()
{
echo __METHOD__, PHP_EOL;
}
}
results.txt
1 2 3 4 5 6
$ php closure-puzzle.php
Bar::A
Bar::B
Bat::C
 
Fatal error: Call to undefined method Bar::D()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.