2015-07-19 137 views
0

當我運行此:PHP函數中的if語句(面向對象)的說法

if ($result->num_rows() > 0) {          
    while($row = $result->fetch_assoc()) {      
      echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; 
    } 
} else { 
    echo "0 results"; 
} 
$conn->close(); 

我收到以下錯誤:

Call to undefined method mysqli_result::num_rows()

我相信錯誤是從num_rows()方法,但可以不太明白什麼是錯的。據我所知,在使用OOP對象$obj->foo()調用方法,但是當我刪除的num_row括號:

if ($result->num_rows > 0) {          
    while($row = $result->fetch_assoc()) {      
      echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>"; 
    } 
} else { 
    echo "0 results"; 
} 
$conn->close(); 

的代碼塊運行正常。

回答

0

第二個代碼塊工作的原因是因爲num_rows是對象的一個​​屬性。使用num_rows()作爲方法會導致未定義的方法錯誤,因爲沒有該名稱的方法。

一個例子:

class Dog { 
    public weight; 
    public age; 

    public function __construct($weight, $age) 
    { 
     $this->weight = $weight; 
     $this->age = $age; 
    } 

    public function bark() 
    { 
     ... 
    } 

    public function gain_weight() 
    { 
     $this->weight++; 
    } 
} 

$dog = new Dog(10, 0); 
$dog->gain_weight(); 
echo $dog->weight; 

gain_weight是一種方法,但weight$dog對象的屬性。

請注意,if ($result->num_rows > 0)if ($result->num_rows)相同,因爲如果$result->num_rows等於0,則該語句將評估爲false。

+0

好吧。所以'num_rows'是由php創建的屬性,而不是一種方法? – Simon

+0

是的。 http://php.net/manual/en/mysqli-result.num-rows.php和整個班級http://php.net/manual/en/class.mysqli-result.php –

+0

你可以看到'$ num_rows'被定義爲一個屬性(aka屬性,成員變量等)。 –