Skip to content

Instantly share code, notes, and snippets.

Last active Apr 4, 2018
What would you like to do?
Error is Warning: Cannot bind an instance to a static closure followed by Fatal error: Using $this when not in object context If the autoloader is just a regular function, the code works as expected. If the executable code in ClosureBug is moved to the bottom of the Autoloader file (with the public static autoloader) everything works as expected.
class Autoloader
// If this is a regular global function instead of public static, everything works
// (with corresponding change to spl_autoloadregister). If it's a non-static, it works
// with the corresponding change to the spl_autoload_register call below as well.
public static function autoload($className)
require_once $className . '.php';
new ClosureBug();
class ClosureBug
private $value = 42;
private $functions = [];
public function addFunction($name, Closure $function)
$this->functions[$name] = $function->bindTo($this, $this);
public function __call($name, $args)
return call_user_func_array($this->functions[$name], $args);
// If this code is at the bottom of autoloader, everything works as expected.
$c = function () {
return $this->value;
$bug = new ClosureBug;
$bug->addFunction('bug', $c);
echo $bug->bug();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment