Home >Backend Development >PHP Tutorial >What\'s New in PHP 5.3: the Condensed Ternary Operator and Anonymous Functions?

What\'s New in PHP 5.3: the Condensed Ternary Operator and Anonymous Functions?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-19 11:24:301064browse

What's New in PHP 5.3: the Condensed Ternary Operator and Anonymous Functions?

Understanding the PHP 5.3 ?: Operator

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.

The New Shorthand ?: Operator

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>

Usage Example

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.

Anonymous Functions in PHP

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn