Coalesce function for PHP?
Many programming languages have a coalesce function (returns the first non-NULL value, example). PHP, sadly in 2009, does not.
What would be a good way to implement one in PHP until PHP itself gets a coalesce function?
There is a new operator in php 5.3 which does this: ?:
// A
echo 'A' ?: 'B';
// B
echo '' ?: 'B';
// B
echo false ?: 'B';
// B
echo null ?: 'B';
Source: http://www.php.net/ChangeLog-5.php#5.3.0
PHP 7 introduced a real coalesce operator:
echo $_GET['doesNotExist'] ?? 'fallback'; // prints 'fallback'
If the value before the ??
does not exists or is null
the value after the ??
is taken.
The improvement over the mentioned ?:
operator is, that the ??
also handles undefined variables without throwing an E_NOTICE
.
First hit for "php coalesce" on google.
function coalesce() {
$args = func_get_args();
foreach ($args as $arg) {
if (!empty($arg)) {
return $arg;
}
}
return NULL;
}
http://drupial.com/content/php-coalesce
链接地址: http://www.djcxy.com/p/9936.html上一篇: 合并运算符自定义隐式转换行为
下一篇: 用于PHP的合并功能?