[英]PHP function as argument in if statement (Object Oriented)
當我運行這個:
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();
我收到以下錯誤:
調用未定義的方法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();
此代碼塊按預期運行。
第二段代碼起作用的原因是因為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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.