2015-07-19 138 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属性,成员变量等)。 –