Laravel 生成器给出:无法重新声明 generatorFunction()

Jac*_*pia 2 php generator laravel

我有以下代码,但是当我运行我的工厂时,出现以下异常:

无法在 /Users/user/Desktop/my-app/database/factories/QuestionFactory.php 中重新声明 questionIndex()(之前在 /Users/user/Desktop/my-app/database/factories/QuestionFactory.php:42 中声明)第 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Wre*_*igh 6

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

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