L. Männer
L. Männer

Reputation: 469

MongoDB return document as instanciated class in PHP

Given a PHP class MyClass:

class MyClass {
   private $a;
   private $b;

   function doSomething() {
      return $this->a + $this->b;
   }
}

Can I create an instance of that class with the result array returned by MongoDB without assigning each value to the class manually? The array has the exact same keys (a and b). Currently, I use the following time-consuming approach:

$result = $mongo->findOne(array('key' => 'value'));
$myClass = new MyClass();
$myClass->a = $result['a'];
$myClass->b = $result['b'];

Upvotes: 0

Views: 30

Answers (1)

Felippe Duarte
Felippe Duarte

Reputation: 15131

You can create dynamic variables:

$result = $mongo->findOne(array('key' => 'value'));
$myClass = new MyClass();
foreach($result as $k => $v) {
    $myClass->{$k} = $v;
}

Don't know if this is a good practice.

Upvotes: 1

Related Questions