为什么在未确定的属性之前使用nullsafe操作员时,我会获得未定义的属性:stdclass ::带有php8?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您似乎对 nullsafe 运算符的作用有轻微的误解。
如果
$reference
为null
,则$reference?->first_name
将返回null
而不会发出任何警告,但是由于$reference
实际上是一个对象,?->
只是像普通对象运算符一样工作,因此会出现未定义的属性警告。You seem to have a slight misunderstanding of what the nullsafe operator does.
If
$reference
wasnull
, then$reference?->first_name
would returnnull
with no warning, but since$reference
is actually an object,?->
just functions like a normal object operator, hence the undefined property warning.如果您有许多嵌套属性,您可以使用 try-catch:
You can use a try-catch in case you have many nested properties: