Laravel data_get帮助程序对数组和对象具有不同的行为

时间:2018-02-21 07:28:41

标签: php laravel laravel-5.4 laravel-5.6

$array = ['key' => null];

echo data_get($array, 'key', 'default') // Result was default
$array = (object) $array;
echo data_get($array, 'key', 'default') // Result was null 

是否有任何具体原因像这样或数组和对象?

Laravel doc ref他们提到了data_get function retrieves a value from a nested array or object using "dot" notation:所以对于数组和对象应该是相同的行为

1 个答案:

答案 0 :(得分:0)

如果您查看data_get()的来源,您会注意到

if (Arr::accessible($target) && Arr::exists($target, $segment)) {
    $target = $target[$segment];
} elseif (is_object($target) && isset($target->{$segment})) {
    $target = $target->{$segment};
} else {
    return value($default);
}

isset($target->{$segment})false返回null,因此会返回对于搜索到的密钥具有null值的对象的默认值。