PHP和?? 操作者

vav*_*ava 5 php

就像有些人所知,C#有非常有用的??运算符,如果左边的表达式为null,则会在右边计算并返回表达式.它对于提供默认值非常有用,例如:

int spaces = readSetting("spaces") ?? 5;
Run Code Online (Sandbox Code Playgroud)

如果readSetting找不到"spaces"并返回null,则变量spaces将保持默认值5.

您可以使用||运算符在JavaScript和Ruby中执行几乎相同的操作,如

var spaces = readSetting("spaces") || 5;
Run Code Online (Sandbox Code Playgroud)

虽然你不可能有0作为的价值spaces在这种情况下,并在JavaScript false中Ruby和JavaScript的.

PHP有or运算符,虽然它不能正常工作,||因为它不会从右边返回表达式,但它在这里仍然有用:

$spaces = readSetting('spaces') or $spaces = 5;
Run Code Online (Sandbox Code Playgroud)

与注意,""并且"0"也像对待false在PHP除了false, 0null大多数语言.

问题是,我应该使用上面的结构吗?除了将大类字符视为虚假之外,它是否有副作用?是否有更好的构造,通常由PHP社区使用和推荐此任务?

Fer*_*yer 6

在这样的情况下更加明确是一个好主意,特别是在PHP中,因为它有一些令人困惑的类型转换规则(例如,如你所指出的,"0"是假的).

如果你想要严格,readSettings如果没有找到设置,让你的函数返回正确的设置或明确定义的值,例如null.然后你应该用它作为:

$spaces = readSettings('spaces');
if (null === $spaces) {
    $spaces = 5;
}
Run Code Online (Sandbox Code Playgroud)

如果你想要更慷慨并且只想要$ space非空,请使用:

$spaces = readSettings('spaces');
if (empty($spaces)) {    // or:  if (!$spaces) {
    $spaces = 5;
}
Run Code Online (Sandbox Code Playgroud)

您可以通过第二个函数调用或丑陋结构(不推荐)的成本来缩短它:

$spaces = readSettings('space') ? readSettings('space') : 5;
$spaces = ($x = readSettings('space')) ? $x : 5;  // UGLY!
Run Code Online (Sandbox Code Playgroud)

但请注意,如果你想0成为一个有效的价值$spaces!

来自Python禅宗:

显式优于隐式.

在你的情况我建议只加第二放慢参数$defaultreadSettings():

function readSettings($key, $default=null) {
    return isset($settings[$key]) ? $settings[$key] : $default;
}

$spaces = readSettings('spaces', 5); 
Run Code Online (Sandbox Code Playgroud)


Pat*_*ien 6

PHP 5.3.0给出了三元运算符条件的较短版本?true:false如下:

$spaces = readSettings('spaces') ?: 5;
Run Code Online (Sandbox Code Playgroud)

请注意,PHP 5.3.0仍然处于测试阶段,尚未准备好生产(虽然它已经是一个候选版本),但它也提供了许多新的酷东西,如lambda函数和命名空间,所以绝对值得检查这些功能!

这篇文章很好地描述了新功能:

http://www.sitepoint.com/article/whats-new-php-5-3/


Kic*_*art 5

PHP 7 现在支持?? 作为空合并运算符

添加了空合并运算符 (??) 作为语法糖,用于需要将三元与 isset() 结合使用的常见情况。如果第一个操作数存在且不为 NULL,则返回;否则返回第二个操作数。

<?php 
// Fetches the value of $_GET['user'] and returns 'nobody' 
// if it does not exist. 
$username = $_GET['user'] ?? 'nobody'; 
// This is equivalent to: 
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';

// Coalescing can be chained: this will return the first 
// defined value out of $_GET['user'], $_POST['user'], and 
// 'nobody'. 
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody'; 
?>
Run Code Online (Sandbox Code Playgroud)

http://php.net/manual/en/migration70.new-features.php


Par*_*ots 1

如果你想保证得到 false 或 null,而不是将“0”之类的东西视为“false”,你可以执行以下操作:

$spaces = readSetting('spaces');
if($spaces == null || $spaces === false) $spaces = 5;
Run Code Online (Sandbox Code Playgroud)

PHP 中的===运算符会查找相同的匹配项,因此“0”、“”不会等于 false。显然,您可能想根据自己的喜好重新设计代码,但您已经明白了。