2011-05-15 133 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