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
Release: 2024-10-19 11:24:30
Original
1062 people have browsed it

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>
Copy after login

However, in PHP 5.3, the middle expression can be omitted, resulting in:

<code class="php">expr ?: val_if_false</code>
Copy after login

This is equivalent to:

<code class="php">expr ? expr : val_if_false</code>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template