PDO's FETCH_INTO $this class does not work

后端 未结 1 1344
情书的邮戳
情书的邮戳 2020-12-03 12:49

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

class user
{
    private $db;
    private $name;

    function __construct($i         


        
相关标签:
1条回答
  • 2020-12-03 13:09

    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_ASSOC);
    $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;
    }
    
    0 讨论(0)
提交回复
热议问题