PHP 5.3是什么?

可能的复制品: PHP 操作符“ ?”和“ :”被调用,它们做什么?

来自 http://twitto.org/

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

Twitto 使用了从 PHP 5.3开始的一些新特性:

  1. DIR常数
  2. 接线员
  3. 匿名函数

  1. 数字2和 PHP 5.3中的 ?:有什么关系?

  2. 还有,匿名函数是什么意思? 这不是已经存在一段时间了吗?

48861 次浏览

?: 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.

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.

Look here:

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.

Anonymous functions: No, they didn't exist before 5.3.0 (see the first note below the examples), at least in this way:

function ($arg) { /* func body */ }

The only way was create_function(), which is slower, quite cumbersome and error prone (because of using strings for function definitions).