Shorthand 三元运算符 PHP - 在 null 上调用成员函数
Shorthand ternary operator PHP - Call to a member function on null
鉴于 class:
<?php
class foo {
public function getGuest() {
return new guest();
}
}
class guest {
public function getGender() {
return 'F';
}
}
我想重构以下工作正常的:
$bar->getGuest() ? $bar->getGuest()->getGender() : NULL
收件人:
$bar->getGuest() ?: $bar->getGuest()->getGender()
哪里出现错误:调用成员函数 getGender() on null
我原以为它会以与顶级版本相同的方式工作,因为据我所知,第二个版本是,如果左侧为真,return 左侧,否则return右手。那么如果左手是假的,为什么右手是 运行?有人可以解释一下吗?
鉴于第二个版本不起作用,顶级版本是否最简洁?
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
让我们看看您在这里尝试做什么:
$bar->getGuest() ?: $bar->getGuest()->getGender()
其工作方式是,如果第一个 $bar->getGuest()
表达式等于 true
,您的操作将 return $bar->getGuest()
本身的值。这应该可以正常工作,没有错误。
但是,如果 $bar->getGuest()
return 是其他内容(例如 null
),它将 运行 第三个表达式,即 $bar->getGuest()->getGender()
。
好吧,我们已经确定 $bar->getGuest()
returned null
,那么你怎么能去 运行 另一个方法 ->getGender()
空值?你不能,这就是你收到错误的原因。
保持代码的可读性和简单性并没有错。您可能想要存储初始方法调用值,因此您不必再次调用它只是为了 运行 getGender()
.
$guest = $bar->getGuest();
$gender = ($guest === null) ? null : $guest->getGender();
鉴于 class:
<?php
class foo {
public function getGuest() {
return new guest();
}
}
class guest {
public function getGender() {
return 'F';
}
}
我想重构以下工作正常的:
$bar->getGuest() ? $bar->getGuest()->getGender() : NULL
收件人:
$bar->getGuest() ?: $bar->getGuest()->getGender()
哪里出现错误:调用成员函数 getGender() on null
我原以为它会以与顶级版本相同的方式工作,因为据我所知,第二个版本是,如果左侧为真,return 左侧,否则return右手。那么如果左手是假的,为什么右手是 运行?有人可以解释一下吗?
鉴于第二个版本不起作用,顶级版本是否最简洁?
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
让我们看看您在这里尝试做什么:
$bar->getGuest() ?: $bar->getGuest()->getGender()
其工作方式是,如果第一个 $bar->getGuest()
表达式等于 true
,您的操作将 return $bar->getGuest()
本身的值。这应该可以正常工作,没有错误。
但是,如果 $bar->getGuest()
return 是其他内容(例如 null
),它将 运行 第三个表达式,即 $bar->getGuest()->getGender()
。
好吧,我们已经确定 $bar->getGuest()
returned null
,那么你怎么能去 运行 另一个方法 ->getGender()
空值?你不能,这就是你收到错误的原因。
保持代码的可读性和简单性并没有错。您可能想要存储初始方法调用值,因此您不必再次调用它只是为了 运行 getGender()
.
$guest = $bar->getGuest();
$gender = ($guest === null) ? null : $guest->getGender();