在 PHP 7.4 中报错:header() expects at least 1 parameter, 0 given (is_callable(‘Header’) 为 true)
1、在 PHP 7.4 中报错:header() expects at least 1 parameter, 0 given。如图1
{ "errors": [ { "debugMessage": "header() expects at least 1 parameter, 0 given", "message": "Internal server error", "extensions": { "category": "internal" }, "locations": [ { "line": 5, "column": 7 } ], "path": [ "onlineStoreSession", "versionedOnlineStore", "theme" ], "trace": [ { "file": "E:\\wwwroot\\object\\Modules\\OnlineStoreThemeGraphQl\\Resolver\\OnlineStoreThemeResolver.php", "line": 96, "function": "header()" }, { "call": "Modules\\OnlineStoreThemeGraphQl\\Resolver\\OnlineStoreThemeResolver::Modules\\OnlineStoreThemeGraphQl\\Resolver\\{closure}(array(4), 'name')" } ] } ], "data": { "onlineStoreSession": { "versionedOnlineStore": { "theme": null } } } }
2、查看具体的代码实现
$fields = array_keys($resolveInfo->getFieldSelection()); return array_reduce($fields, function($carry, $field) use($fieldResolvers){ if (isset($fieldResolvers[$field])) { $carry[$field] = is_callable($fieldResolvers[$field])? $fieldResolvers[$field](): $fieldResolvers[$field]; } return $carry; }, []);
3、打印 $fields ,结果如下
$fields = array_keys($resolveInfo->getFieldSelection()); print_r($fields); exit;
Array ( [0] => id [1] => editable [2] => createdAt [3] => editedAt [4] => name [5] => role [6] => previewable [7] => url [8] => themeStoreThemeId [9] => metadata [10] => presets [11] => themeSettingsCategories )
4、添加判断,当 $field 等于 name 时,打印 $fieldResolvers[$field]、is_callable($fieldResolvers[$field])
$fields = array_keys($resolveInfo->getFieldSelection()); return array_reduce($fields, function($carry, $field) use($fieldResolvers){ if (isset($fieldResolvers[$field])) { if ($field == 'name') { var_dump($fieldResolvers[$field]); var_dump(is_callable($fieldResolvers[$field])); exit; } $carry[$field] = is_callable($fieldResolvers[$field])? $fieldResolvers[$field](): $fieldResolvers[$field]; } return $carry; }, []);
string(6) "Header" bool(true)
5、is_callable — 验证值是否可以在当前范围内作为函数调用。is_callable(‘Header’) 为 true,因为调用了 header() — 发送原生 HTTP 头,参数是必填的,进而报错。instanceof 用于确定一个 PHP 变量是否属于某一类 class 的实例。Closure 用于代表 匿名函数 的类。调整为 $fieldResolvers[$field] instanceof \Closure 后,不再报错。
$fields = array_keys($resolveInfo->getFieldSelection()); return array_reduce($fields, function($carry, $field) use($fieldResolvers){ if (isset($fieldResolvers[$field])) { $carry[$field] = ($fieldResolvers[$field] instanceof \Closure) ? $fieldResolvers[$field](): $fieldResolvers[$field]; } return $carry; }, []);
近期评论