2

我使用 if 语句来确定在函数中返回什么,但它似乎没有按照我想要的方式工作。

function DoThis($dogs, $cats){
// do something with dogs, pet them perhaps.

$reg = $dogs[0];
$nate = $dogs[1];

if($cats = "dave"){return $reg;}
if($cats = "tom"){return $nate;}

}

$cats是一个字符串(如果有帮助的话),输入时不会产生任何回报。如果我手动设置退货,那是可行的,但由于某种原因上面没有。

4

3 回答 3

6

要测试是否相等,请使用 ==(双等号)运算符而不是 =(单等号)运算符。

例如:

if("dave" == $cats){return $reg;}
if("tom"  == $cats){return $nate;}
于 2009-12-03T22:35:05.490 回答
6

您使用的是赋值运算符而不是比较运算符。请尝试以下操作。

 $cats == "dave"
 $cats == "tom"

当你说

 if($cats = "dave") { ... }

你真的在说

  1. 将值“dave”分配给变量 $cats
  2. 如果变量 $cats 在赋值后为真,则返回真。否则,返回假

这是一个常见的错误,并且困扰着老手和新手。

于 2009-12-03T22:35:27.500 回答
2

您需要使用 == 进行比较。

= is an assignment, so it has the effect of setting $cats to "dave" and then (because the expression evaluates to "dave", which is non-empty) it treats the if statement as being "if (true) ..." and executes the contained code.

于 2009-12-03T22:37:08.653 回答