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 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助