Req #62043 [Com]: new operator
| From: | reeze dot xia at gmail dot com | Date: | Wed, 16 May 2012 06:09:04 +0000 |
| Subject: | Req #62043 [Com]: new operator | ||
| References: | 1 | Groups: | php.bugs |
| Request: | Send a blank email to php-bugs+get-170491@lists.php.net to get a copy of this message | ||
Edit report at https://bugs.php.net/bug.php?id=62043&edit=1
ID: 62043
Comment by: reeze dot xia at gmail dot com
Reported by: piotrekz5 at wp dot pl
Summary: new operator
Status: Open
Type: Feature/Change Request
Package: PHP options/info functions
Operating System: any
PHP Version: Irrelevant
Block user comment: N
Private report: N
New Comment:
Do you mean this operator?
$a = $a ?: "default value");
http://www.php.net/manual/en/language.operators.comparison.php#language.operators.
comparison.ternary
Previous Comments:
------------------------------------------------------------------------
[2012-05-16 00:31:03] phpmpan at mpan dot pl
---- BEGIN CODE ----
function ifNull($var, $value, $null = NULL) {
return ($var !== $null)? $var : $value;
}
----- END CODE -----
Or even simpler to use and, unlike previous, working fine with undefined variables:
---- BEGIN CODE ----
function unNull(&$var, $value, $null = NULL) {
if ($var === $null) {
$var = $value;
}
return $var;
}
----- END CODE -----
If we drop the last argument even multiple operands version can be achieved:
---- BEGIN CODE ----
function nonNull() {
return array_reduce(func_get_args(), function(&$a, $e) {
return ($a === NULL && $e !== NULL)? $e : $a;
});
}
----- END CODE -----
Any reason to not do this in userland?
------------------------------------------------------------------------
[2012-05-15 23:23:20] piotrekz5 at wp dot pl
Description:
------------
Hi,
Let's implement a new operator - '??' (used in c#).
The ?? operator is called the null-coalescing operator and is used to define a default value. It
returns the left-hand operand if the operand is not null; otherwise it returns the right operand.
Test script:
---------------
example:
$var1 = null;
$var2 = null;
$var3 = $var1 ?? $var2; //$var3==null
$var4 = $var1 ?? 'default1'; //$var4=='default1'
$var5 = $var1 ?? $var2 ?? 'default2'; //$var5=='default2'
$var6 = $var2 ?? $var3 ?? $var4 ?? 'default3'; //$var6=='default1' since the
first non-null value is $var4=='default1'
------------------------------------------------------------------------
--
Edit this bug report at https://bugs.php.net/bug.php?id=62043&edit=1