drfals1307 2015-08-26 18:48
浏览 23
已采纳

PDO:fetchClass没有设置父类的属性

So I've got three classes:

class GenericObject{
    private $parentThing
}

class MiddleObject extends GenericObject{
     private $middleThing
}

class ChildObject extends MiddleObject{
     private $childThing;    
}

and when I call pdoDatabaseThing->fetchAll(PDO::FETCH_CLASS, "ChildObject");, all of the properties defined in MiddleObject are null, though the properties defined in ChildObject and GenericObject are set as expected.

Is this expected behavior, or am I just missing a bug somewhere in my code? Is there a known workaround?

  • 写回答

1条回答 默认 最新

  • duanen19871021 2015-08-27 16:56
    关注

    It looks like this is an expected behavior. The ChildObject doesn't know about the private fields of the parent classes since they are private in that classes and thats the whole point. When the parent fields are at least protected you can set the field because the ChildObject class can use them as intended.

    <?php
    class ParentClass {
        protected $bar;
    
        public function getBar() {
            return $this->bar;
        }
    }
    class ChildClass extends ParentClass {
        private $foo;
    
        public function getFoo() {
            return $this->foo;
        }
    }
    
    $dbh = new PDO('mysql:host=localhost', 'test');
    $stmt = $dbh->query('SELECT "someValue" AS foo, "another value" as bar');
    $all = $stmt->fetchAll(PDO::FETCH_CLASS, 'ChildClass');
    $obj = $all[0];
    var_dump($obj);
    var_dump($obj->getFoo(), $obj->getBar());
    

    This will generate the following output:

    object(ChildClass)#3 (2) {
      ["foo":"ChildClass":private]=>
      string(9) "someValue"
      ["bar":protected]=>
      string(13) "another value"
    }
    string(9) "someValue"
    string(13) "another value"
    

    If you change the visibility of the parents field to private you will get the situation you already have observed, having the parents private fields still be at NULL:

    object(ChildClass)#3 (3) {
      ["foo":"ChildClass":private]=>
      string(9) "someValue"
      ["bar":"ParentClass":private]=>
      NULL
      ["bar"]=>
      string(13) "another value"
    }
    string(9) "someValue"
    NULL
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?