|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2013-05-02 13:39 UTC] netmosfera at gmail dot com
Description:
------------
<?
class Test
{
public $clos;
public $bobo = 22;
static function blah(){
return new static(function(){ echo $this->bobo; });
}
function __construct(\Closure $c)
{
$this->clos = $c->bindTo($this, $this);
}
}
// perfectly fine when closure is declared in global space
$a = new Test(function(){ echo $this->bobo; });
$clos = $a->clos;
$clos();
// binding doesn't work when closure is declared in a static method
$a = Test::blah();
$clos = $a->clos;
$clos();
// results in: Warning: Cannot bind an instance to a static closure
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Nov 26 22:00:01 2025 UTC |
I understand the issue of scope here, but imho the location of where the closure is not relevant. You get the same error when you do: public static function somemethod() { // construct the a new object $instance = static::factory(); // get the current event object $event = \Event::getInstance(); // setup a shutdown event $event->on('shutdown', function($event) { $this->process(); }, $instance); } where the "on" method is trying to bind $instance (which is an object, so there should be no issue, $this is defined), but fails with this same error.To illustrate, I now have to this to get it to work: class Dummy { public function __construct($event, $object) { // setup a shutdown event for writing cookies $event->on('shutdown', function($event) { $this->process(); }, $object); } } new Dummy($event, $instance); which does exactly the same, but now the closure is defined in an object context. Which is insane...I've looked into the code, and indeed, it simply bails out when you want to bind an object to the closure and it's initially created as ZEND_ACC_STATIC. So instead of if ((newthis != NULL) && (closure->func.common.fn_flags & ZEND_ACC_STATIC)) { zend_error(E_WARNING, "Cannot bind an instance to a static closure"); } it should change the scope of the closure (as the bindTo will provide an object to bind to, which implicitly changes the context of the closure. Since the closure is effectively recreated, it shouldn't be an issue changing the scope while doing that.