Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP PDO: Do the fetch styles FETCH_CLASS and FETCH_INTO fetch into private object properties?

Tags:

database

php

pdo

Pretty short question, here is an example:

$prepared = $this->pdo->prepare("SELECT * FROM Users WHERE ID = :ID");
$statement = $prepared->execute(array(":ID" => $User_ID))
$result = $statement->fetchAll(PDO::FETCH_CLASS, "User");
//OR
$User = new User();
$result = $statement->fetch(PDO::FETCH_INTO, $User);

(written from top of the head, could contain syntax errors)

Do those two directly fetch into the private properties of said objects? I read it also circumvents the __construct function, so will it circumvent private status too?

like image 589
sinni800 Avatar asked Sep 02 '11 11:09

sinni800


2 Answers

Very short answer: Yes it will.

class Foo
{
    private $id;
    public function echoID()
    {
        echo $this->id;
    }
}
$result = $statement->fetchAll(PDO::FETCH_CLASS, "Foo");
$result[0]->echoID(); // your ID

Aside:

This will cause syntax errors $statement->fetchAll(PDO::FETCH_INTO, $User);. You can't use FETCH_INTO with the fetchAll method.

like image 78
cwallenpoole Avatar answered Oct 11 '22 11:10

cwallenpoole


But event with PDO::FETCH_CLASS there is a problem for private properties for subclasses. E.g.

class Animal
{
    private $color;
    public function getColor()
    {
        return $this->color;
    }
}
class Cat extends Animal
{
}

$statement->setFetchMode(PDO::FETCH_CLASS, "Cat" );
$someCat = $statement->fetch();

echo $someCat->getColor();  //empty
print_r( $someCat );
/*
now have strange output like:
[color:Animal:private] => 
[color] => grey
*/

But if you set the property to protected - it works fine

like image 37
Олег Всильдеревьев Avatar answered Oct 11 '22 12:10

Олег Всильдеревьев