Shopware 6插件:已检查数组键存在仍触发‘Undefined Array Key’警告?
Shopware 6:已检查数组键仍触发“Undefined Array Key”警告的原因及解决办法
问题场景
开发Shopware 6插件时,在管理员路由对应的控制器动作中执行以下代码,尽管已用array_key_exists检查数组键是否存在,仍收到“Undefined array key”警告:
$customFields = $order->getCustomFields(); $optin = null; if (array_key_exists('swag_product_reviews_optin', $customFields)) { $optin = $customFields['swag_product_reviews_optin']; } $text .= ' » Optin: ' . $optin;
收到的警告信息
Warning: Undefined array key "swag_product_reviews_optin"
堆栈跟踪片段
#0 /home/wokljnlu/sw66demo.wo-kaufen.de/vendor/symfony/http-kernel/HttpKernel.php(178): Swag\ProductReviews\Administration\Controller\SwagProductReviewsTestMailController->orderWhyNot() #1 /home/wokljnlu/sw66demo.wo-kaufen.de/vendor/symfony/http-kernel/HttpKernel.php(76): Symfony\Component\HttpKernel\HttpKernel->handleRaw() ...
原因分析
核心问题在于$order->getCustomFields()的返回值并非始终是数组:
- 返回null的情况:当订单未设置任何自定义字段时,该方法会返回
null而非空数组。此时array_key_exists的第二个参数为null,PHP会抛出警告,若后续逻辑分支判断失误,访问数组键时就会触发“Undefined array key”提示。 - 返回对象的情况:在部分场景下,
getCustomFields()可能返回实现了ArrayAccess接口的Struct对象,而array_key_exists仅对原生数组生效,无法识别对象的偏移量,导致检查失效,后续访问键时触发警告。
优化解决办法
推荐两种更安全的处理方式:
方式1:先确保$customFields为数组,再使用null合并运算符
$customFields = $order->getCustomFields() ?? []; $optin = $customFields['swag_product_reviews_optin'] ?? null; $text .= ' » Optin: ' . $optin;
?? []确保当getCustomFields()返回null时,$customFields被初始化为空数组。?? null直接处理键不存在的情况,无需额外条件判断,简洁且安全。
方式2:使用isset结合数组检查
$customFields = $order->getCustomFields(); $optin = null; if (is_array($customFields) && isset($customFields['swag_product_reviews_optin'])) { $optin = $customFields['swag_product_reviews_optin']; } $text .= ' » Optin: ' . $optin;
- 先通过
is_array()验证$customFields是数组,避免非数组类型传入isset()导致的问题。 isset()同时检查键存在且值不为null,适合需要排除值为null场景的需求。
内容的提问来源于stack exchange,提问作者Auhona
相关产品推荐
相关产品推荐

