【问题标题】:Is there a workaround for $this within a closure in PHP 5.3?在 PHP 5.3 的闭包中有 $this 的解决方法吗?
【发布时间】:2014-01-23 10:24:12
【问题描述】:

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

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

}

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    如果 info 方法是公开的,你可以这样做:

    //...
    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 中,闭包中的上下文与对象上下文不同。

    【讨论】:

      猜你喜欢
      • 2015-05-16
      • 2012-12-23
      • 1970-01-01
      • 2011-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      相关资源
      最近更新 更多