Home > Article > Backend Development > 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.
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!