2011-05-15 129 views
0

我想要使用if语句来使用布尔值,它不起作用。顶部是我使用的函数,底部是if语句。当我将if语句更改为false时,我会得到结果,但我需要true和false布尔值。任何提示无法返回一个函数的布尔值在php

 public function find($key) { 
    $this->find_helper($key, $this->root);  
} 

public function find_helper($key, $current){ 
    while ($current){ 
     if($current->data == $key){ 
      echo " current"; 
      return true; 
     } 
     else if ($key < $current->data){ 
      $current= $current->leftChild; 
      //echo " left "; 
      } 
     else { 
      $current=$current->rightChild; 
      //echo " right "; 
      } 
    } 
    return false; 
} 


     if($BST->find($randomNumber)){//how do I get this to return a true value? 
     echo " same "; 
} 

回答

7

您从find_helper()而不是从find()返回。如果没有return(见下文),find_helper()方法被调用,但无论该方法返回的是丢弃。因此,您的find()方法最终返回既不值值(PHP翻译为空)。

public function find($key) { 
    return $this->find_helper($key, $this->root);  
} 
+0

谢谢你这么多,我不能相信我错过了 – Aaron 2011-05-15 17:05:25

+0

请注明答案的答案。 – hakre 2011-05-15 17:29:40

0

使用三元运算

public function find($key) { 
    return ($this->find_helper($key, $this->root)) ? true : false;  
    } 
+1

问题在于缺少'return',而不是三元运算符。此外,辅助方法已经返回true/false;你为什么需要重复它? – BoltClock 2011-05-15 17:03:43

+0

是啊有点无用 – Ascherer 2011-05-15 17:04:50

+0

如果您稍后在简单的if语句中使用返回值,则这是多余的。另外你应该考虑(bool)哪个更容易阅读。 – hakre 2011-05-15 17:05:19