PHP变量变量

时间:2009-10-21 21:30:41

标签: php mysql

我正在写这个评论课:

class Comment {

    public $id;
    public $post_id;
    public $name;
    public $email;
    public $website;
    public $body;
    public $date;
    public $ip_address;
    public $status;

    function __construct($id) {

        global $db;

        $resc = $db->query("SELECT * FROM blog_comments WHERE id='$id' LIMIT 1");

        while($row = $db->fetch_assoc($resc)) {
            while ($comment = current($row)) {
                $key = key($row);
                $this->$key = $comment{$key};
                next($row);
            }
        }
    }
}

以下是构造函数中的查询在数据库中运行时将返回的内容:

query results http://17webshop.com/wp-content/uploads/2009/10/Picture-2.png

但是当我运行它时,这就是print_r(new Comment(1));吐出:

Comment Object
(
    [id] => 1
    [post_id] => 1
    [name] => J
    [email] => j
    [website] => h
    [body] => b
    [date] => 1
    [ip_address] => :
    [status] => 1
)

为什么我只获得每个领域的第一个角色?

感谢。

3 个答案:

答案 0 :(得分:6)

你想要

$comment[$key]

$ comment {$ key}将为您提供字符串的第n个字符。由于$ key本身是一个字符串,因此PHP将其转换为整数0并获得第一个字符。

答案 1 :(得分:3)

当前/下一步是痛苦的,我不确定{}解除引用是什么。

为什么不呢:

$resc = $db->query("SELECT * FROM blog_comments WHERE id='$id' LIMIT 1");

while($row = $db->fetch_assoc($resc)) {
    foreach($row as $key=>$value){
       $this->$key = $value;
    }
}

答案 2 :(得分:2)

我认为您需要更改此行:

$this->$key = $comment{$key};

使用:

$this->$key = $comment[$key];