PHP是否有像perl这样的默认赋值用法? [英] Does PHP have a default assignment idiom like perl?

查看:63
本文介绍了PHP是否有像perl这样的默认赋值用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Perl中,如果我想默认一个可能存在的值,例如作为传入的参数,我可以这样做:

In Perl, if I want to default a value that might exist, for example as a passed in parameter, I can do this:

  $var = parm->('variable') || 'default';

在PHP中是否有类似的东西?分配后是否必须检查该值,如果该值仍为null,则将其分配为默认值?

Is there something analogous in PHP or do I have to check the value after assigning, and if it is still null assign it the default value?

推荐答案

不完全是

PHP 5.3引入了所谓的三进制快捷方式".

PHP 5.3 introduced what they call "the ternary shortcut".

// old way
$foo = $foo ? $foo : 'default';

// new way in 5.3
$foo = $foo ?: 'default';

什至没有那么多的快捷方式,它仅适用于可短路的值(如果0$foo的有效值,则此快捷方式将失败.)

Which isn't even that much of a shortcut and only works short-circuit-able values (if 0 is a valid value for $foo this shortcut will fail.)

否则,您将必须检查旧的,困难的手动方式的类型/存在性.

Otherwise you'll have to do the type/existence checking the old, hard, manual way.

您还可以为签名中的参数指定默认值-不确定这是否正是您要得到的,但实际上就是这样

You can also specify default values for parameters in the signature - not sure if that's exactly what you're getting at but here's that in action

function foo( $bar = 'baz' )
{
  echo $bar;
}

foo(); // baz

这篇关于PHP是否有像perl这样的默认赋值用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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