Is there a workaround for $this within a closure in PHP 5.3?

后端 未结 1 663
-上瘾入骨i
-上瘾入骨i 2021-01-23 17:33

My IDE warns me that $this is not allowed within a closure before PHP 5.4. Is there a workaround for this without upgrading PHP from 5.3.10 ? See fire()

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-23 18:19

    If info method is public you can do:

    //...
    public function fire()
    {
        $self = $this;
        $self->info('Starting chunk');
        Item::chunk(1000, function($items) use ($self)
        {
            foreach ($items as $item)
            {
                $self->info($item->img);
            }
        }
        );
    
    }
    //...
    


    If info is private you can't and you need to upgrade to php 5.4, because in PHP 5.3 the context in the closure is not the same of the object context.

    0 讨论(0)
提交回复
热议问题