更简洁的三元表达? [英] More concise ternary expression?

查看:69
本文介绍了更简洁的三元表达?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常发现自己需要使用以下逻辑模式编写代码:

I often find myself needing to write code with the following logical pattern:

$foo = isset($bar) ? $bar : $baz;

我知道?:语法:

$foo = $bar ?: $baz;

...从表面上看,这正是我想要的;但是,当未设置 $ bar 时,它将引发未定义的通知索引。它还使用与 empty()相同的逻辑,这意味着像 FALSE ,<$ c $这样的空值c> 0 , 0 等不通过。因此,这并不是真的等效。

...which, on the surface, appears to be what I'm looking for; however, it throws an undefined notice index when $bar is not set. It also uses the same logic as empty(), meaning that "empty" values like FALSE, 0, "0", etc. don't pass. Hence, it's not really equivalent.

$ bar 未设置?

编辑:

要多做一些清除为什么我正在寻找一种快捷语法,这是一个更好的示例:

To make it a bit more clear why I'm looking for a shortcut syntax, here's a better example:

$name = isset($employee->getName())
      ? $employee->getName()
      : '<unknown>';

在这种情况下, $ employee 可能是一个来自第三方库的对象,并且它的名称可能为 NULL 可能是一个有效的方案。我想将变量 $ name 设置为返回的名称(如果有的话),但是如果没有则设置一些明智的默认值。

In this case, $employee might be an object from a 3rd-party library, and it might be a valid scenario that its name might be NULL. I'd like to set variable $name to the returned name (if there is one), but some sensible default if there isn't.

如果方法调用不仅仅是获取方法,那么示例变得更加冗长,因为我们必须缓存结果:

If the method call is more complex than just a getter, then the example becomes even more verbose, since we have to cache the result:

$bar = $some->reallyExpensiveOperation();
$foo = isset($bar) ? $bar : $baz;


推荐答案

当您使用时,我只会使用简写三元语法明确地预定义变量或将对象与魔术吸气剂配合使用。这是一个非常基本的示例,说明我通常在哪里使用速记三元语法

I would only use the short hand ternary syntax when you explicitly predefine your variables or use an object with a magic getter. This is a very basic example of where I would normally use short hand ternary syntax

class Foo {
    public function __get($name) {
        return isset($this->{$name}) ? $this->{$name} : '';
    }
}

$foo = new Foo();
$bar = $foo->baz ?: 'default';

这篇关于更简洁的三元表达?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆