在PHP 5.3的闭包中是否有针对$ this的解决方法? [英] Is there a workaround for $this within a closure in PHP 5.3?

查看:56
本文介绍了在PHP 5.3的闭包中是否有针对$ this的解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的IDE警告我,PHP 5.4之前的闭包中不允许使用$this.有没有从5.3.10升级PHP的解决方法?请参见下面的fire()方法:

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() method below:

<?php

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;


class UpdateItemImageSizes extends Command {

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'namespace:updateimagesizes';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Updates image size information in the items table.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function fire()
    {
        $this->info('Starting chunk');
        Item::chunk(1000, function($items)
        {
            foreach ($items as $item)
            {
                $this->info($item->img);
            }
        }
        );

    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return array(
            //array('example', InputArgument::REQUIRED, 'An example argument.'),
        );
    }

    /**
     * Get the console command options.
     *
     * @return array
     */
    protected function getOptions()
    {
        return array(
            array('example', null, InputOption::VALUE_OPTIONAL, 'An example option.', null),
        );
    }

}

推荐答案

如果info方法是公共的,则可以执行以下操作:

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);
        }
    }
    );

}
//...


如果info是私有的,则不能,并且您需要升级到php 5.4,因为在PHP 5.3中,闭包中的上下文与对象上下文不同.


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.

这篇关于在PHP 5.3的闭包中是否有针对$ this的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆