为什么在未确定的属性之前使用nullsafe操作员时,我会获得未定义的属性:stdclass ::带有php8?

发布于 2025-01-20 22:28:22 字数 633 浏览 5 评论 0原文

PHP 8.0 引入了 nullsafe 运算符,可以像 $foo?->bar?->baz; 一样使用。 我有一个在 php 8.1 上运行的代码示例,即使它使用 nullsafe 运算符,也会抛出错误 Undefined property: stdClass::$first_name

$reference = (object) $reference; // Cast of array to object

return [
    'FirstName' => $reference?->first_name,
];

要解决该错误,我必须使用 null 合并运算符:

$reference = (object) $reference; // Cast of array to object

return [
    'FirstName' => $reference->first_name ?? null,
];

为什么 nullsafe 运算符在这种情况下会抛出错误?

Php 8.0 introduced the nullsafe operator which can be used like so $foo?->bar?->baz;.
I have a code sample running on php 8.1 that throws the error Undefined property: stdClass::$first_name even though it is using the nullsafe operator:

$reference = (object) $reference; // Cast of array to object

return [
    'FirstName' => $reference?->first_name,
];

To solve the error, I have to use the null coalescing operator:

$reference = (object) $reference; // Cast of array to object

return [
    'FirstName' => $reference->first_name ?? null,
];

Why is the nullsafe operator throwing an error in this case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

似梦非梦 2025-01-27 22:28:22

您似乎对 nullsafe 运算符的作用有轻微的误解。

如果 $referencenull,则 $reference?->first_name 将返回 null 而不会发出任何警告,但是由于 $reference 实际上是一个对象,?-> 只是像普通对象运算符一样工作,因此会出现未定义的属性警告。

You seem to have a slight misunderstanding of what the nullsafe operator does.

If $reference was null, then $reference?->first_name would return null with no warning, but since $reference is actually an object, ?-> just functions like a normal object operator, hence the undefined property warning.

北风几吹夏 2025-01-27 22:28:22

如果您有许多嵌套属性,您可以使用 try-catch:

try {
    if ($response->foo->bar->foo->bar->status == 'something') {
        ...
    }
} catch (\ErrorException $ex) {
    // Property missing exception will be caught here
}

You can use a try-catch in case you have many nested properties:

try {
    if ($response->foo->bar->foo->bar->status == 'something') {
        ...
    }
} catch (\ErrorException $ex) {
    // Property missing exception will be caught here
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文