问题描述
在 Python 中可以做到:
foo = {}
assert foo.get('bar', 'baz') == 'baz'
在 PHP 中可以使用三元运算符,例如:
In PHP one can go for a trinary operator as in:
$foo = array();
assert( (isset($foo['bar'])) ? $foo['bar'] : 'baz' == 'baz' );
我正在寻找高尔夫版本.我可以在 PHP 中做得更短/更好吗?
I am looking for a golf version. Can I do it shorter/better in PHP?
assert($foo['bar'] ?? 'baz' == 'baz');
看起来 Null 合并运算符 ??
是 今天值得一试.
在下面的评论中找到 (+1)
推荐答案
我刚刚想出了这个小助手函数:
I just came up with this little helper function:
function get(&$var, $default=null) {
return isset($var) ? $var : $default;
}
这不仅适用于字典,也适用于所有类型的变量:
Not only does this work for dictionaries, but for all kind of variables:
$test = array('foo'=>'bar');
get($test['foo'],'nope'); // bar
get($test['baz'],'nope'); // nope
get($test['spam']['eggs'],'nope'); // nope
get($undefined,'nope'); // nope
为每个引用传递以前未定义的变量不会导致 NOTICE
错误.相反,通过引用传递 $var
将定义它并将其设置为 null
. 如果传递的变量为 .还要注意 spam/eggs 示例中隐式生成的数组:
Passing a previously undefined variable per reference doesn't cause a NOTICE
error. Instead, passing $var
by reference will define it and set it to null
. The default value will also be returned if the passed variable is null
. Also note the implicitly generated array in the spam/eggs example:
json_encode($test); // {"foo":"bar","baz":null,"spam":{"eggs":null}}
$undefined===null; // true (got defined by passing it to get)
isset($undefined) // false
get($undefined,'nope'); // nope
请注意,即使 $var
是通过引用传递的,get($var)
的结果将是 $var
的副本,不做参考.我希望这会有所帮助!
Note that even though $var
is passed by reference, the result of get($var)
will be a copy of $var
, not a reference. I hope this helps!
这篇关于有没有更好的 PHP 方法可以通过数组(字典)中的键获取默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!