如果在 if 表达式和 if 语句中都使用相同的函数,它是否会被调用两次


If the same function is used in both if expression and if statement, does it get called twice?

以下构造是否访问数据库两次?

$output = access_database() ? access_database() : NULL;

我应该做以下事情吗?

$result = access_database();
$output = $result ? $result : NULL;

当你这样做时: $result = access_database(); result接收函数执行时的值,而不是访问时将执行的引用。

所以,是的,以下行将执行您的函数两次:

$output = access_database() ? access_database() : NULL;

一种选择是使用 elvis 运算符(php 版本>= 5.3):

$output = access_database() ?: NULL;

是的。使用这个PHP语法糖来避免这种情况。

$output = access_database() ? : NULL;