1

In MySQL I have a table with the columns ID and name.

A query to the DB will give me each query row as an array:

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

I also have a PHP class

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

How do I write a construtor for Person such that I can go

$current = new Person($row);

echo $current->ID; // 3
echo $current->name; // John
arney
  • 795
  • 7
  • 20
  • Maybe I should have mentioned that I am not looking to for something like `$this.ID = $row['ID']` but rather an automatism, as this is just a minimal example for a high dimensional problem – arney May 25 '13 at 18:09
  • 1
    BTW, the concept you're describing is Object Relational Mapping (ORM) http://en.wikipedia.org/wiki/Object-relational_mapping, if you're looking for a library that provides this (as opposed to implementing yourself as a learning experience) Doctrine and Propel are a couple of popular ones for PHP. – John Carter May 26 '13 at 01:31

1 Answers1

1

Just like variable variables, you can have variable properties:

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;
        }
    }
}

You might want to make this a static method (fromRow?) though, to avoid the mess of overloading in PHP. You might also want to filter the keys; that depends on the situation.

Here’s a demo!

Ry-
  • 218,210
  • 55
  • 464
  • 476