Created
January 3, 2013 15:57
-
-
Save anonymous/4444468 to your computer and use it in GitHub Desktop.
Attaching PHP Closures/Anonymous Functions a Class/Object
This file contains hidden or 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 | |
/** | |
* references: | |
* http://www.murraypicton.com/2010/09/extending-objects-using-anonymous-functions-in-php/ | |
* http://php.net/manual/en/functions.anonymous.php | |
* http://php.net/manual/en/function.is-callable.php | |
*/ | |
class Foo { | |
public $bar; | |
public function __call($method, $args) { | |
if(isset($this->$method) === true) { | |
$func = $this->$method; | |
$func(); | |
} | |
} | |
} | |
$obj = new Foo; | |
$obj->bar = function() { | |
echo "Inside Foo::bar()\n"; | |
}; | |
var_dump($obj->bar); // prints out that we have a closure | |
var_dump(method_exists($obj,'bar')); // return false (WHY!?!?!?!) | |
var_dump(is_callable(array($obj,'bar'), true, $callable_name)); // returns true | |
var_dump($callable_name); // prints Foo::bar (even though it isn't a static function) | |
$obj->bar(); //Will generate a fatal error as the method doesn't exist if we don't have the __call method in Foo | |
$func = $obj->bar; | |
$func(); //Outputs "Inside Foo:bar()" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment