如何从一个类中返回多个数据库记录在OOP编程 [英] how can i return multiple database record from a class in OOP programming

查看:88
本文介绍了如何从一个类中返回多个数据库记录在OOP编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个类似这样的类

  class book {
public $ title;
public $ author;
public $ page_num;
.....
....

public function show_book($ limit = 1){
....
$ result = mysql_query(SELECT title,author,page_num FROM book limit = $ limit);

while($ row = mysql_fetch_array($ result))
{
$ this-> title = $ row ['title'];
$ this-> author = $ row ['author'];
$ this-> page_num = $ row ['page_num'];
}

}

  $ book = new book(); 
$ book-> show_book();
echo $ book-> title。。$ book-> author ......;






这只适用于一本书
如果我想显示7本书?
这不适用于 $ book-> show_book($ limit = 7);
i可以做7个对象,但我认为有更好的方法

解决方案

我要重命名函数 show_books 数组 book 对象。当没有匹配项时,返回一个空数组,否则返回所有匹配的元素。

  public static function show_books($ limit = 1)这是一个静态方法,而不是一个实例方法。 {
....
$ result = mysql_query(SELECT title,author,page_num FROM book limit = $ limit);
$ books = array();

while($ row = mysql_fetch_array($ result))
{
$ book = new book();
$ book-> title = $ row ['title'];
$ book-> author = $ row ['author'];
$ book-> page_num = $ row ['page_num'];
$ books [] = $ book;
}
return $ books;
}

$ books = Book :: show_books(7);


Lets say i have a class like this

class book {
    public $title;
    public $author;
    public $page_num;
        .....
        ....

 public function show_book($limit=1){
         .... 
        $result = mysql_query("SELECT title,author,page_num  FROM book limit=$limit");

         while($row = mysql_fetch_array($result))
          {
         $this->title=$row['title'];
         $this->author=$row['author'];
         $this->page_num=$row['page_num'];
          }

        }

and then i can use it like :

 $book = new book();
 $book->show_book();
 echo $book->title." ".$book->author ...... ;


this works for one book what if i want to show 7 books ? this is not working for $book->show_book($limit=7); i can make 7 objects but i think there's a better way

解决方案

I'd rename the function show_books and have it return an array of book objects. When you have no matches you return an empty array, otherwise you return all of the matching elements. It probably makes the most sense as a static method rather than an instance method.

public static function show_books($limit=1){
     .... 
    $result = mysql_query("SELECT title,author,page_num  FROM book limit=$limit");
    $books = array();

     while($row = mysql_fetch_array($result))
     {
          $book = new book();
          $book->title=$row['title'];
          $book->author=$row['author'];
          $book->page_num=$row['page_num'];
          $books[] = $book;
     }
     return $books;
}

$books = Book::show_books(7);

这篇关于如何从一个类中返回多个数据库记录在OOP编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆