Php 如何从数据库中检索数据作为对象?

Php 如何从数据库中检索数据作为对象?,php,oop,Php,Oop,在Lynda.com PHP with MySQL Beyond the Basics中,作者Kevin Skoglund介绍了以下方法,作为从数据库中检索数据作为对象的一种方法: public static function find_by_id($id) { global $database; $id = $database->escape($id); $result_array = static::find_by_sql

在Lynda.com PHP with MySQL Beyond the Basics中,作者Kevin Skoglund介绍了以下方法,作为从数据库中检索数据作为对象的一种方法:

    public static function find_by_id($id)
    {
        global $database;
        $id = $database->escape($id);
        $result_array = static::find_by_sql("SELECT * FROM " . static::$table_name . " WHERE id = {$id} LIMIT 1");
        return !empty($result_array) ? array_shift($result_array) : false;
    }

    public static function find_by_sql($sql)
    {
        global $database;
        $result_set = $database->query($sql);
        $object_array = array();
        while ($row = $database->fetch_array($result_set))
        {
            $object_array[] = static::instantiate($row);
        }

        return $object_array;
    }

    protected static function instantiate($record)
    {
        $class_name = get_called_class();
        $object = new $class_name();
        foreach ($record as $attribute => $value)
        {
            if ($object->has_attribute($attribute))
            {
                $object->$attribute = $value;
            }
        }
        return $object;
    }
例如,在用户类中使用此选项的示例如下:

$user = User::find_by_id(1);
echo $user->first_name;
我的问题是,如果我有一个post表,例如,一个名为“user”的列作为外键,并且我尝试使用上述方法检索post,那么user属性将只是一个数字

$post = Post::find_by_id(1);
echo $post->user; // This will return the id of the user
但是,我希望能够做到以下几点:

echo $post->user->first_name;

我怎样才能完成那样的事情?它会涉及使用连接吗?提前感谢。

请阅读此文档。本页介绍对象之间的映射关联


你想要一个ORM。。例如,为了学习的目的,我想为自己建立一些简单的东西。