What\'s the ?: Operator in PHP 5.3?

DDD
Release: 2024-10-19 12:52:02
Original
417 people have browsed it

What's the ?: Operator in PHP 5.3?

The ?: Operator in PHP 5.3

PHP 5.3 introduced the ?: operator, a condensed form of the conditional operator that was previously available. Originally, the conditional operator took the form:

expr ? val_if_true : val_if_false
Copy after login

In PHP 5.3, you can omit the middle part, leading to the ?: syntax. This is equivalent to:

expr ? expr : val_if_false
Copy after login

For example, the following code checks if the variable $c is callable. If it isn't, it throws an exception:

require __DIR__.'/c.php';
if (!is_callable($c = @$_GET['c'] ?: function() { echo 'Woah!'; }))
    throw new Exception('Error');
$c();
Copy after login

Anonymous Functions in PHP 5.3

Along with the ?: operator, PHP 5.3 also introduced anonymous functions. Contrary to the question, anonymous functions have not existed for a while. They were a new feature in PHP 5.3. Anonymous functions are created without a name and are typically used as callbacks or as arguments to other functions.

In the example above, the anonymous function is assigned to the variable $c. It has no parameters and prints "Woah!" when called. This anonymous function is used as a default value for the $c variable, which checks if the function is callable before attempting to execute it.

The above is the detailed content of What\'s the ?: Operator in PHP 5.3?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!