The ternary conditional operator in PHP has long been a staple of the language, allowing for concise if-then-else statements. In PHP 5.3, this operator gained a new form that further streamlines its usage.
Previously, the ternary operator took the form:
<code class="php">expr ? val_if_true : val_if_false</code>
However, in PHP 5.3, the middle expression can be omitted, resulting in:
<code class="php">expr ?: val_if_false</code>
This is equivalent to:
<code class="php">expr ? expr : val_if_false</code>
Consider the following example:
<code class="php">require __DIR__.'/c.php'; if (!is_callable($c = @$_GET['c'] ?: function() { echo 'Woah!'; })) throw new Exception('Error'); $c();</code>
Here, the ?: operator is used to assign a default value to the $c variable if the condition @$_GET['c'] evaluates to false. If @$_GET['c'] is not set or is an invalid function, $c will be assigned the anonymous function that displays "Woah!" to the user.
As for anonymous functions, they have indeed existed in PHP for a while, but they gained new versatility in PHP 5.3. Anonymous functions, also known as closures, allow you to define functions inline without giving them a name.
In the example above, the anonymous function is defined as:
<code class="php">function() { echo 'Woah!'; }</code>
It can be invoked like any other named function, using the $c variable in this case.
The above is the detailed content of What\'s New in PHP 5.3: the Condensed Ternary Operator and Anonymous Functions?. For more information, please follow other related articles on the PHP Chinese website!