-3

我的 PHP 片段

function CheckNumber($number){
 if($number==100){
   return true;
 else{
   return false;
 };
}

我希望速记(三元运算符)if语句做同样的事情,但这不起作用:

function CheckNumber($number){
  $result = ($number==100) ? return true : return false;
  echo $result;
}

我知道echo这里肯定是错误的,但是我应该怎么做才能将结果返回result给函数呢?

4

1 回答 1

6
return $number == 100;

== already results in a boolean, no need to do an if on it and create another boolean for it. You also don't need to assign this intermediate boolean to a variable.

Your particular problem is that return is a statement and cannot be part of an expression. If at all, the code needs to look like:

$result = $number == 100 ? true : false;
return $result;

But again, that can be reduced to the version above.

于 2013-08-04T18:05:24.497 回答