赋予变量默认值的最佳方法(模拟Perl ||,|| =) [英] Best way to give a variable a default value (simulate Perl ||, ||= )

查看:83
本文介绍了赋予变量默认值的最佳方法(模拟Perl ||,|| =)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在Perl中做这种事情:$foo = $bar || $baz如果$bar为空或未定义,则将$baz分配给$foo.您还具有$foo ||= $bletch,如果$foo未定义或为空,则只会将$bletch分配给$foo.

I love doing this sort of thing in Perl: $foo = $bar || $baz to assign $baz to $foo if $bar is empty or undefined. You also have $foo ||= $bletch which will only assign $bletch to $foo if $foo is not defined or empty.

在这种情况下,三元运算符既乏味又累人.当然可以在PHP中使用一种简单,优雅的方法吗?

The ternary operator in this situation is tedious and tiresome. Surely there's a simple, elegant method available in PHP?

还是使用isset()的自定义函数的唯一答案?

Or is the only answer a custom function that uses isset()?

推荐答案

在PHP 7中,我们终于有了一种优雅的方法.它称为空合并运算符.您可以像这样使用它:

In PHP 7 we finally have a way to do this elegantly. It is called the Null coalescing operator. You can use it like this:

$name = $_GET['name'] ?? 'john doe';

这等效于

$name = isset($_GET['name']) ? $_GET['name']:'john doe';

这篇关于赋予变量默认值的最佳方法(模拟Perl ||,|| =)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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