PHP PDO:作为对象获取数据-调用在__construct之前分配的属性.这样对吗? [英] PHP PDO: Fetching data as objects - properties assigned BEFORE __construct is called. Is this correct?

查看:80
本文介绍了PHP PDO:作为对象获取数据-调用在__construct之前分配的属性.这样对吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完整的问题应该是这是正确的还是我不能指望的一些错误?"

为什么这是正确的行为?

WHY is this correct behavior?

我一直在与PDO合作,尤其是在将数据直接提取到对象中的过程中.这样做时,我发现了这一点:

I've been working with PDO more and in particular playing with fetching data directly into objects. While doing so I discovered this:

如果我直接将数据提取到这样的对象中:

If I fetch data directly into an object like this:

$STH = $DBH->prepare('SELECT first_name, address from people WHERE 1');
$obj = $STH->fetchAll(PDO::FETCH_CLASS, 'person');

并有一个这样的对象:

class person {
  public $first_name;
  public $address;

  function __construct() {
    $this->first_name = $this->first_name . " is the name";
  }
}

它向我展示了在调用__construct之前已分配属性-因为名称全都附加了是名称".

It shows me that the properties are being assigned before the __construct is being called -- because the names all have " is the name" appended.

是这个错误(在这种情况下,我无法/不会依靠它)还是应该的方式".因为它目前的工作方式确实很不错.

Is this some bug (in which case I can't/won't count on it) or is this The Way It Should Be. Because it's really quite a nice thing the way it works currently.

显然,根据维护者之一, 这不是一个错误.有人在2008年将其发布为错误,回答是不是错误,请阅读文档".

Apparently, according to one of the maintainers this is not a bug. Someone posted it as a bug in 2008, to which the reply was 'its not a bug, read the docs'.

但是,我真的很想知道为什么这是正确的行为.

However, I'd really like to know WHY this is correct behavior.

推荐答案

经过大量阅读,我认为我终于找到了答案:它是有意地这样工作的,您可以选择使其以其他方式运行.

After much reading I think I finally came across the answer: it works this way intentionally, and you have the option of making it operate otherwise.

有一个几乎没有文献记载的PDO常量,称为PDO::FETCH_PROPS_LATE,您可以使用它使属性在构造后被提取到对象中.例如:

There's a mostly undocumented PDO constant called PDO::FETCH_PROPS_LATE which you can use to cause the properties to be fetched into the object after its been constructed. For example:

$obj = $STH->fetchAll(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'person');

将导致在创建对象后分配属性,因此上面的示例完全不会修改属性.当然,不使用PDO::FETCH_PROPS_LATE会使它按照我在原始问题中的示例中所述进行操作.

Will cause the properties to be assigned AFTER the object is created, so my example above would not modify the properties at all. Leaving the PDO::FETCH_PROPS_LATE off, of course, causes it to act as described in my example in the original question.

维护者似乎已经积极考虑到这两种行为都是可取的,并且可以选择两种方法中的任一种.该文档甚至没有解释它-我正在阅读PDO常量列表看到了,然后试了一下.

The maintainers seem to have actively considered that both behaviors may be desirable and given you the option to do either. The documentation doesn't even explain it -- I was reading through a list of PDO constants and saw it, and gave it a shot.

这篇关于PHP PDO:作为对象获取数据-调用在__construct之前分配的属性.这样对吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆