tags:

views:

57

answers:

2

I want to populate class with constructor using FETCH_INTO of PDO:

class user
{
    private $db;
    private $name;

    function __construct($id)
    {
        $this->db = ...;

        $q = $this->db->prepare("SELECT name FROM users WHERE id = ?");
        $q->setFetchMode(PDO::FETCH_INTO, $this);
        $q->execute(array($id));

        echo $this->name;
    }
}

This does not working. No error, just nothing. Script has no errors, FETCH_ASSOC works fine.

What is wrong with FETCH_INTO?

A: 

Total guess, but it could very well be that FETCH_INTO just doesn't work for the $this reference. Have you tried temporarily pulling that code out of the class to check?

Matchu
I at first also think so, but then found http://dase.googlecode.com/svn-history/r1555/trunk/lib/Dase/DBO.php (search for FETCH_INTO), seams it is working. I tried this code with FETCH_ASSOC - it is working. So, i can assign them directly, just wandering why not FETCH_INTO.
Qiao
+2  A: 

You have two errors in your code:

1) You forgot $q->fetch()

 ...
 $q->execute(array($id));
 $q->fetch(); // This line is required

2) But even after adding $q->fetch() you'll get this:

Fatal error: Cannot access private property User::$name in ...

So, as you can see, PDO cannot access private members even if it is called inside class method.

Here is my solution:

...
$q->execute(array($id));
$q->setFetchMode(PDO::FETCH_INTO);
$data = $q->fetch();
foreach ($data as $propName => $propValue)
{
    // here you can add check if class property exists if you don't want to
    // add another properties with public visibility
    $this->{$propName} = $propValue;
}
Sergiy
You can also just make `$name` a public variable. It sure sounds like one.
Matchu
Adding public properties is not always good idea
Sergiy