pg_fetch_object神秘的缺少类值

问题描述

| 我在传递自定义类时pg_fetch_object()返回空对象时遇到问题。
class foo {
    protected $_data = array();

    public function __construct(array $data = array()) {
        $this->_data = array(
            \'foo_id\' => null,\'parent_id\'  => null,\'type\' => \'region\',\'name\' => null,\'description\' => \'\',);

        foreach ($data as $key => $val) {
            $this->__set($key,$val);
        }
    }

    public function __set($key,$val) {
        echo \"SETTING $key -> $val\";
        var_dump($this->_data);
        $this->_data[$key] = $val;
    }

    public function __get($key) {
        return $this->_data[$key];
    }
}
然后我叫这个
 $tmp = pg_fetch_object($result,$current_row,\"foo\");
 var_dump($tmp);
我得到这个输出
SET foo_id => 55925
array(0) { }
SET name => All
array(1) { [\"foo_id\"]=> string(5) \"55925\" }
SET searchable => ALL
array(2) { [\"foo_id\"]=> string(5) \"55925\" [\"name\"]=> string(3) \"All\" }
SET parent_id =>
array(3) { [\"foo_id\"]=> string(5) \"55925\" [\"name\"]=> string(3) \"All\"                 [\"searchable\"]=> string(3) \"ALL\" }
SET type => region
array(4) { [\"foo_id\"]=> string(5) \"55925\" [\"name\"]=> string(3) \"All\"     [\"searchable\"]=> string(3) \"ALL\" [\"parent_id\"]=> NULL }
SET sub_count => 96
array(5) { [\"foo_id\"]=> string(5) \"55925\" [\"name\"]=> string(3) \"All\" [\"searchable\"]=> string(3) \"ALL\" [\"parent_id\"]=> NULL [\"type\"]=> string(6) \"region\" }
SET description =>
array(6) { [\"foo_id\"]=> string(5) \"55925\" [\"name\"]=> string(3) \"All\" [\"searchable\"]=> string(3) \"ALL\" [\"parent_id\"]=> NULL [\"type\"]=> string(6) \"region\"     [\"sub_count\"]=> string(2) \"96\" } asdfasdfasdfasdfasdf

object(Dao_Region)#23 (2) {
  [\"_data\":protected]=>
  array(5) {
    [\"foo_id\"]=>
    NULL
    [\"parent_id\"]=>
    NULL
    [\"type\"]=>
    string(6) \"region\"
    [\"name\"]=>
    NULL
    [\"description\"]=>
    string(0) \"\"
  }
}
为什么即使我的设置员被解雇,我的$ tmp变量也具有所有初始值? 当我在pg_fetch_object()调用中将\“ foo \”更改为StdClass时,出现了问题。     

解决方法

        pg_fetch_row实例化传递给它的类,并设置以数据库中字段名称命名的属性。 EG,pg_fetch_row做类似的事情:
$record = pg_fetch_assoc()
$class = new $passedClassName();
foreach($record as $field => $val) $class->$field = $val;
return $class;
如上面的代码所示,它不会将其值的数组传递给构造函数。 因此,pg_fetch_row将照常实例化foo类,不向其构造函数传递任何参数,您的代码允许这样做,并将$ data参数默认为空数组,设置默认值,然后退出。 在我伪造的示例中,我们在日志中看到的对__set的调用在foreach循环中触发。那里发生了奇怪的事情;值应该在数组中。尝试删除构造函数,看看是否可以解决问题……     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...