title: Can I make PDOStatement->fetchObject not use non-member variables?
body: <p>Lets say I have a class like this:</p>
  
  <pre><code>Class User {
    var $id
    var $name;
  }
  </code></pre>
  
  <p>And I run a query using PDO in php like so:</p>
  
  <pre><code>$stm = $db-&gt;prepare('select * from users where id = :id');
  $r = $stm-&gt;execute(array(':id' =&gt; $id));
  $user = $r-&gt;fetchObject('User');
  </code></pre>
  
  <p>If I vardump my user object it has all kinds of other fields in it that I have not defined in the User class. Obviously I could make my query specific so that it only gives me back the fields I need/want. But if I don't want to do that is there any way to make this work the way I want it to?</p>
  
  <p>I like the idea of fetchObject, because it's one line of code to create this object and set member variables for me. I just don't want it to set variables I haven't defined in my class.</p>
  
  <p>EDIT:</p>
  
  <p>Well it seems like karim79 is right and the fetch or fetchObject won't work the way I want it to. I've added the following bit of code after I do the fetch to get the desired results.</p>
  
  <pre><code>$valid_vars = get_class_vars('User');
  foreach (get_object_vars($user) as $key =&gt; $value) {
      if (!array_key_exists($key, $valid_vars)) {
          unset($user-&gt;$key);
      }
  }
  </code></pre>
  
  <p>Obviously not the most elegant solution :/ I'm going to extend the PDOStatement class and add my own method fetchIntoObject or something like that and automatically do these unsets. Hopefully shouldn't be to much overhead, but I want to be able to easily fetch into an object with 1 line of code :)</p>
  
  <p>SUPER EDIT:</p>
  
  <p>Thanks to mamaar's comment I went back to the documentation again. I found what the problem is. <a href="http://us.php.net/manual/en/pdo.constants.php" rel="nofollow noreferrer">http://us.php.net/manual/en/pdo.constants.php</a> and scroll down to PDO::FETCH_CLASS and it explains that the magic method __set() is used if properties don't exist in the class. I overwrote the method in my target class and tada, works. Again, not the most elegant solution. But now I understand the WHY, and that's important to me :D</p>