duanfan8699 2015-11-11 20:46
浏览 122
已采纳

在PHP三元速记运算符中使用isset()时获取变量的值

In using the shorter ternary operator:

$foo = isset($_GET['bar']) ?: 'hello';

If $_GET['bar'] is set, is it possible for $foo to return the value of $_GET['bar'] instead of true?

Edit: I understand the old school ternary works e.g.,

$foo = isset($_GET['bar']) ? $_GET['bar'] : 'hello';

but I want to use the newschool ternary which is the even shorter version

  • 写回答

5条回答 默认 最新

  • douhao2856 2015-11-11 21:00
    关注

    It sounds like you are asking about the new (as of PHP 7) null coalesce operator. You can do something like:

    $foo = $_GET['bar'] ?? 'hello';
    echo $foo;
    

    Which if $_GET['bar'] is null will set $foo to hello.

    The first operand from left to right that exists and is not NULL. NULL if no values are defined and not NULL. Available as of PHP 7.

    Functional demo: https://3v4l.org/0CfbE

    $foo = $_GET['bar'] ?? 'hello';
    echo $foo . "
    ";
    $_GET['bar'] = 'good bye';
    $foo = $_GET['bar'] ?? 'hello';
    echo $foo;
    

    Output:

    hello
    good bye
    

    Additional reading on it: http://www.lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”