【问题标题】:Laravel generator gives: Cannot redeclare generatorFunction()Laravel 生成器给出:无法重新声明 generatorFunction()
【发布时间】:2018-08-16 09:03:12
【问题描述】:

我有以下代码,但是当我运行我的工厂时,我得到了以下异常:

无法重新声明 questionIndex()(之前在 /Users/user/Desktop/my-app/database/factories/QuestionFactory.php:42) 在 /Users/user/Desktop/my-app/database/factories/QuestionFactory.php 第 46 行

当我运行我的单元测试时会发生这种情况,而这个特定的工厂现在不在测试中。我有其他工厂有一个生成器,但函数的名称完全不同。被称为autoIncrement()

<?php

use Faker\Generator as Faker;

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| This directory should contain each of the model factory definitions for
| your application. Factories provide a convenient way to generate new
| model instances for testing / seeding your application's database.
|
*/

$questionIndex = questionIndex();

$factory->define(App\Models\Question::class, function (Faker $faker, $overrides) use ($questionIndex) {

    $question = [
        'How is 2 + 2?',
        'Choose, what is the possibility to win the lottery?',
        'According to the Big Brother, is 2 + 2 = 5?'
    ];

    $questionType = [
        'numeric',
        'multiple-choice',
        'true-or-false'
    ];

    $index = $questionIndex->current();
    $questionIndex->next();
    return [
        'title' => $question[$index],
        'type' => $questionType[$index],
        'category_id' => $overrides['category_id']
    ];

});

function questionIndex() {
    for ($i = 0; $i < 100000; $i++) {
        yield $i%3;
    }
}

【问题讨论】:

    标签: php laravel generator


    【解决方案1】:

    您可以使用function_exists检查您定义的函数是否存在,它不允许重新声明

    if (!function_exists('questionIndex')) {
        function questionIndex() {
            for ($i = 0; $i < 100000; $i++) {
                yield $i%3;
            }
        }
    }
    

    【讨论】:

    • 我试过但没有给出:Error: Call to undefined function questionIndex()
    【解决方案2】:

    尝试使用函数声明屏蔽/保护,以防文件被包含两次,那么函数将不会被重新声明。

    if (!function_exists('questionIndex')) {
        function questionIndex() {
            for ($i = 0; $i < 100000; $i++) {
                yield $i%3;
            }
        }
    }
    

    【讨论】:

    • 我试过但没有给出:Error: Call to undefined function questionIndex()
    • 那是因为你在上面调用了函数,在调用之前尝试移动函数声明。
    • 按照@Wreigh 的建议,在使用之前移动函数声明并清除缓存。
    猜你喜欢
    • 2016-04-29
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多