Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephdpurcell/4444481 to your computer and use it in GitHub Desktop.
Save josephdpurcell/4444481 to your computer and use it in GitHub Desktop.
Attaching PHP Closures/Anonymous Functions a Class/Object
<?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()"
@xeoncross
Copy link

Don't forget about __callStatic() and __isset() for this type of thing. Also, you don't need to get the value:

        return $this->{$method}($args);

or

        return call_use_func_array(array($this, $method), $args);

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