Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ?: in PHP 5.3? [duplicate]

Possible Duplicate: What are the PHP operators “?” and “:” called and what do they do?

From http://twitto.org/

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

Twitto uses several new features available as of PHP 5.3:

  1. The DIR constant
  2. The ?: operator
  3. Anonymous functions

  1. What does number 2 do with the ?: in PHP 5.3?

  2. Also, what do they mean by anonymous functions? Wasn't that something that has existed for a while?

like image 666
JasonDavis Avatar asked Jan 28 '10 08:01

JasonDavis


People also ask

What is?: in PHP?

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise. The only way was create_function() , which is slower, quite cumbersome and error prone (because of using strings for function definitions).

What is ?: In Java?

The ternary conditional operator ?: allows us to define expressions in Java. It's a condensed form of the if-else statement that also returns a value.


2 Answers

?: is a form of the conditional operator which was previously available only as:

expr ? val_if_true : val_if_false 

In 5.3 it's possible to leave out the middle part, e.g. expr ?: val_if_false which is equivalent to:

expr ? expr : val_if_false 

From the manual:

Since PHP 5.3, it is possible to leave out the middle part of the conditional operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

like image 57
Ben James Avatar answered Sep 23 '22 01:09

Ben James


The ?: operator is the conditional operator (often refered to as the ternary operator):

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

In the case of:

expr1 ?: expr2 

The expression evaluates to the value of expr1 if expr1 is true and expr2 otherwise:

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

like image 27
Gumbo Avatar answered Sep 24 '22 01:09

Gumbo