2014-07-31 12:43
浏览 19


So far I've used many objects in my applications but often if I had to for example display for example users' profiles on page I simply got 20 users from database as array using some method in my object and assigned it to view.

Now I want to create application more with models that represent real data. So for each user I should probably have User object with properties .

Here I put sample code to get users from database and to display them in PHP:


$db = new mysqli('localhost', 'root', '', 'mytest');

class User
    private $id;
    private $name;

    public function __construct($data)
        foreach ($data as $k => $v) {
            if (property_exists($this, $k)) {
                $this->$k = $v;

    public function show()
        return $this->id . ' ' . $this->name ;

$result = $db->query("SELECT * FROM `user` LIMIT 20");

$users = array();
while ($data = $result->fetch_object()) {
    $data->x = 10; // just to test if property isn't created
    $users[] = new User($data);

// displaying it on page
foreach ($users as $user) {
    echo $user->show() . "<br />";


  1. Is it the way I should use data from database into model? I mean if should I create object for each record even if the only role of this object would be returning some data to view (for example even not modified by any functions as in this example). Of course I know that often data should be prepared to display or made some calculations or additional data should be retrieved from database before those data could be used to display.

  2. Is there any way to assign object properties from database simpler than using constructor with loop?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dsx5201 2014-07-31 13:19

    First of all, i'd move the DB operations in a separate class, not inline with the User class. You could create an abstract Model class, which the User class would extend and add DB logic to it.

    You'd have a select() method to query the database, which would return an array of objects of the class that extended the Model class (the User class in this case).

    To answer your questions:

    1. I think it's ok. Most ORMs work this way.
    2. An alternative would be to assign the user row data from the DB to a $data attribute in your User class and use the magic methods __get and __set to access them.
    点赞 打赏 评论

相关推荐 更多相似问题