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

前端 未结 4 768
我在风中等你
我在风中等你 2020-12-17 23:06

Pretty short question, here is an example:

$prepared = $this->pdo->prepare(\"SELECT * FROM Users WHERE ID = :ID\");
$statement = $prepared->execute(         


        
相关标签:
4条回答
  • 2020-12-17 23:40

    You could try:

    class Foo {
        private $id;
        public function __set($prop, $val) {
            $this->$prop = $val;
        }
        public function __get($prop) {
            return $this->$prop;
        }
    }
    
    $result = $statement->fetchAll(PDO::FETCH_CLASS, "Foo");
    $result[0]->id();
    
    0 讨论(0)
  • 2020-12-17 23:46

    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.

    0 讨论(0)
  • 2020-12-17 23:46

    The reason you can't access private properties on a super class is because those properties are out of scope. Subclasses don't take on the private attributes of their parent classes, including variables and functions.

    edit: Thanks for clarifying your question but it does make my answer look a bit ridiculous here. :p

    0 讨论(0)
  • 2020-12-17 23:52

    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

    0 讨论(0)
提交回复
热议问题