Matthew Fonda wrote (on 17/09/2014):
Hi Andrea,

This is great -- thanks to you and Nikita for the work here.

Syntax wise, I would prefer a function-like syntax, e.g. coalesce($a, $b,
'c') or ifsetor() instead of $a ?? $b ?? 'c'. I find this more readable,
and it avoids any possible confusion about precedence within the
expressions. Either way, still +1 for this feature.

Funnily enough, the standard library at my workplace has long included a coalesce() function as below, which is indeed very handy; there is also a coalesce_empty(), which calls empty($arg) instead of is_null($arg). Both pre-date the shorthand ?: operator, which could replace coalesce_empty(); the proposed ?? could replace coalesce()

As mentioned in the PHPDoc, the downside of a function is that it can't short-cut evaluation if the first argument passes, whereas an operator can. It would be possible to work around this by defining a special "language construct" rather than a real function, but that's probably more confusing than it's worth.

The special case for $first is a performance optimisation because func_get_args() has rather a lot of overhead; I'm guessing 5.6's variadic signatures ($args...) are less painful (can anyone confirm?)

/**
 * coalesce
 * PHP analogue of the SQL Coalesce() function
 * @param an arbitrary number of arguments
* @return the first argument which is not NULL; If all arguments are NULL, will return NULL
 *
 * coalesce( $a, $b ) is equivalent to ($a === NULL ? $a : $b)
 * but coalesce( hard_work(), 'default' ) only has to do hard_work() once
* [OTOH, coalesce( $a, hard_work() ) has to do hard_work() even if the result gets thrown away]
 */
function coalesce($first)
{
    if (!is_null($first))
    {
        return $first;
    }

    foreach ( func_get_args() as $arg )
    {
        if ( ! is_null($arg) )
        {
            return $arg;
        }
    }
}

--
Rowan Collins
[IMSoP]

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to