dongzhi1851 2015-07-19 15:09
浏览 48
已采纳

PHP函数作为if语句中的参数(面向对象)

when I run this:

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();

I get the following error:

Call to undefined method mysqli_result::num_rows()

I presume the error is from the num_rows() method but can't quite figure out what is wrong. As far as I know, objects call methods by using $obj->foo() in OOP but when I remove the parenthesis of 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();

this block of code runs as expected.

  • 写回答

1条回答 默认 最新

  • doulan8846 2015-07-19 15:12
    关注

    The reason the second block of code works is because num_rows is an attribute of the object. Using num_rows() as a method results in a undefined method error because there is no method by that name.

    An example:

    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 is a method, but weight is an attribute of the $dog object.

    On a side note, if ($result->num_rows > 0) is the same as if ($result->num_rows) since if $result->num_rows equals 0, the statement will evaluate to false.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图