As you can read in manual:在类中创建closure后,它将自动绑定伪变量$this.然后,您的实例将具有两个引用:When the closure has been created inside the class, it'll bound automatically the pseudo-variable $this. Then your instance will have two references: $MyAutoLoader变量; Closure传递给spl_autoload_register.$MyAutoLoader variable;Closure passed to spl_autoload_register.我用一些不同之处重写了您的示例,您可以看到其行为:I've rewritten your example with a few differences which you can see the behavior:class MyAutoLoader { private $instance = "Outside"; public function registerAutoLoader(Closure $closure = null) { //If a closure ins't passed as parameter, a new one will be created if (!$closure instanceof Closure) { $this->instance = "Inside"; //A closure created inside a class will bound the pseudo-variable $this $closure = function ($class) {}; } spl_autoload_register($closure); } public function __destruct() { printf('Destroying: %s - %s instance<br/>' , get_class($this) , $this->instance); }}$MyAutoLoader = new MyAutoLoader();$MyAutoLoader->registerAutoLoader();$MyAutoLoader2 = new MyAutoLoader();//A closure created outside of a class doesn't have the class scope$MyAutoLoader2->registerAutoLoader(function($class){});unset($MyAutoLoader , $MyAutoLoader2);echo 'End of script<br/>';结果将是:Destroying: MyAutoLoader - Outside the instanceEnd of scriptDestroying: MyAutoLoader - Inside the instance在最后一个示例中,Closure已在类范围之外创建.因此,只有变量$MyAutoLoader2具有该类的实例.In the last example, the Closure has been created out of the class scope. So only the variable $MyAutoLoader2 has the instance of the class.另一个可能的例子是:class MyAutoLoader { public function registerAutoLoader(Closure $closure) { //Binding the class scope to the closure $closure = $closure->bindTo($this); spl_autoload_register($closure); } public function __destruct() { printf('Destroying: %s <br/>' , get_class($this)); }}$MyAutoLoader = new MyAutoLoader();$MyAutoLoader->registerAutoLoader(function($class){});unset($MyAutoLoader);echo 'End of script<br/>';在最后一个示例中,我在类外部创建了Closure,但是我将类范围绑定到了该类中,从而创建了对MyAutoLoader类的新引用.结果将是:In this last example, I'm creating the Closure outside of class, but I'm binding the class scope into the class, creating a new reference to MyAutoLoader class. The result will be:End of scriptDestroying: MyAutoLoader bind和bindTo的其他一些技巧,您可以在下面的链接中阅读:A few more tips from bind and bindTo you can read at the link below: 如何我可以调用ReflectionFunction包装使用$ this的闭包吗? 这篇关于如果对象注册了spl_autoload_register(),则该对象直到脚本结束才被销毁.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
09-22 20:29