数据库行对象属性

时间:2013-05-25 15:53:38

标签: php constructor

在MySQL中,我有一个包含IDname列的表格。

对DB的查询会将每个查询行作为数组提供:

$row = array('ID' => '3', 'name' => 'John');

我还有一个PHP类

class Person {
    var $ID = '';
    var $name = '';
}

我如何为Person写一个construtor,以便我可以去

$current = new Person($row);

echo $current->ID; // 3
echo $current->name; // John

1 个答案:

答案 0 :(得分:1)

就像变量变量一样,您可以拥有变量属性:

class Person {
    var $ID = '';
    var $name = '';

    public function __construct($row) {
        foreach($row as $key => $value) {
            # `$this->$key =` sets the property of $this named whatever’s in $key.
            $this->$key = $value;
        }
    }
}

你可能想让它成为一个静态方法(fromRow?),以避免PHP中的重载混乱。您可能还想过滤键;这取决于具体情况。

Here’s a demo!