"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What\'s the ?: Operator in PHP 5.3?

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

Published on 2024-11-08
Browse:884

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

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

expr ? expr : val_if_false

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();

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.

Release Statement This article is reprinted at: 1729305795 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3