Skip to content

Instantly share code, notes, and snippets.

@dstockto dstockto/Autoloader.php
Last active Apr 4, 2018

Embed
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.
<?php
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';
}
}
spl_autoload_register('Autoloader::autoload');
new ClosureBug();
<?php
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
You can’t perform that action at this time.