简体   繁体   English

PHP 速记布尔值

[英]PHP Shorthand Boolean

I'm trying to shorten the following.我正在尝试缩短以下内容。 Essentially I want to always get the value of the lefthand as long as $object isn't null, otherwise use a default value.本质上,只要 $object 不为空,我就希望始终获得左手的值,否则使用默认值。

if ($object) {
    $isManual = $object->getIsManual(); // either true or false
} else {
    $isManual = true;
}

The following doesn't work since getIsManual can return false which makes it use the righthand.以下不起作用,因为 getIsManual 可以返回 false 这使得它使用右手。

$isManual = $object ? $object->getIsManual() : true;

Any work arounds?任何解决方法? Currently on PHP 7.4.目前在 PHP 7.4 上。

Just to clarify - the return value of getIsManual() wouldn't affect the condition, it only evaluates $object to be 'true' or 'false' (which include null).只是为了澄清 - getIsManual()的返回值不会影响条件,它只会将$object评估$object “true”或“false”(包括 null)。

You can explicitly check for null in the condition...您可以在条件中明确检查 null ...

$isManual = is_null($object) ? true : $object->getIsManual();

Note that I've reversed the order of the values as I prefer to say is is_null rather than using a not as well.请注意,我已经颠倒了值的顺序,因为我更喜欢说is_null而不是使用 not 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM