未定义的索引 - isset guard 不适用于 helper

Undefined Index - isset guard doesn't work with helper

我有一个来自 post 请求的多维数组。它看起来像这样:$request['bags'][1]['fruits']。有时,这个值不存在,所以它 returns 未定义的索引错误。

$model->fruits = $request['bags'][1]['fruits'];

如果我在我的控制器中使用 isset guard,它可以工作

$model->fruits = isset($request['bags'][1]['fruits'];) ? $request['bags'][1]['fruits'] : '';
$model->save();

现在,我想把它包装在一个函数中,这样我就可以使用类似 nullable($fruits) 的东西来完成它。


现在,我尝试将它包装在辅助方法中;所以我创建了 Helper.php 并在里面添加了这个方法:

function nullable($value) {
    return (isset($value)) ? $value : '';
}

但是在我的控制器中,当我调用 nullable() 时,它抛出未定义索引错误。

nullable($request['bags'][1]['fruits']); // Undefined Index

isset($request['bags'][1]['fruits']) ? $request['bags'][1]['fruits'] : ''; // works

您遇到的问题是,一旦请求未定义索引,就会抛出未定义索引通知。一旦您想在使用 nullable($request['bags'][1]['fruits']) 调用辅助函数时访问键后面的值,就会发生这种情况。该值被提取然后发送给函数

您可以改为使用 PHP 中的 null coalesce operator ??

$model->fruits = $request['bags'][1]['fruits'] ?? '';

如果您真的想创建自己的辅助函数,则需要以某种方式进行,即在将参数传递给函数时不访问该字段。

这可以通过从您要访问的键中分离数组来完成。

function nullable(array $array, ...$keys) {
    $current = $array;
    foreach($keys as $key) {
        if (!isset($current[$key])) {
            return NULL;
        }
        $current = $current[$key];
    }
    return $current;
}

然后调用将是 nullable($request, 'bags', 1, 'fruits');

Code example

你能用吗condition? true : false :

意思是:

$model->fruits = $request['bags'][1]['fruits'] ? $request['bags'][1]['fruits'] : '';

或:

$model->fruits = $request['bags'][1]['fruits'] ?? '';