0

I have a class with id, keyword and value. I'm fetching data from a table named Setting into the class Setting using

if ($stmt->execute()) {
  $o = $stmt->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, "Setting", array('id', 'keyword','value'));
}

When I look at the content of $o I see the following

Array ( [0] => Setting Object ( [id] => id [keyword] => keyword [value] => value [Id] => 1 [Keyword] => AdminMail [Value] => yahoo@yahoo.com ))

My class looks like this

class Setting {
var $id;
var $keyword;
var $value;

function __construct($id,$ke,$va) {
    $this->id = $id;
    $this->keyword = $ke;
    $this->value = $va;
}

public function getKeyword() {
    return $this->keyword;
}

public function getValue() {
    return $this->value;
}
}

I expect that $o->getValue returns yahoo@yahoo.com but it returns value.

Can someone tell my why "[id] => id [keyword] => keyword [value] => value" appears before the actual output from my table?

  • The problem was in the fetchAll command. The names in array('id', 'key', 'value') was not the same as in the table I was quering from. – Peter Larsen Oct 13 '13 at 19:56

1 Answers1

0

I have no idea, why this tricky syntax sugar is so attractive.
How it's better than plain, simple and readable code like this:

function __construct($init) {
    $this->id      = $init['id'];
    $this->keyword = $init['ke'];
    $this->value   = $init['va'];
}
...
$stmt->execute();
$o = new Settings($stmt->fetchAll());
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • It is not working. I get an empty Setting object withou any data in it. – Peter Larsen Oct 13 '13 at 18:14
  • Well, this code weren't intended to be copy-pasted but rather to show the regular and usual way of initializing objects. Are you familiar with it? Do you understand the code I posted? – Your Common Sense Oct 13 '13 at 18:24
  • If I understood the code correctly the $stmt->fetchAll() should generate an array that is passed to the constructor, that sets all the fields to the value in the array. Is that correct? – Peter Larsen Oct 13 '13 at 18:32
  • Yes, this was the intention. Nothing complex at all. Did your query return any data? Do you have error reporting on? – Your Common Sense Oct 13 '13 at 18:36