Php 在类构造函数中设置动态属性
pdo语句Php 在类构造函数中设置动态属性,php,pdo,Php,Pdo,pdo语句 class QuestionVO { public $qtype; function __construct() { //echo $this->qtype; //it's not empty and displays value $this->{$this->qtype} = true; } 这是致命的错误 然而,这份文件说 此fetch方法允许您直接将数据提取到所选的类中。当您使用fetch_类时,对象的属性将在调用构造函数之前设置 致命错误:无法
class QuestionVO {
public $qtype;
function __construct() { //echo $this->qtype; //it's not empty and displays value
$this->{$this->qtype} = true;
}
这是致命的错误
然而,这份文件说
此fetch方法允许您直接将数据提取到所选的类中。当您使用fetch_类时,对象的属性将在调用构造函数之前设置
致命错误:无法访问QuestionVO中的空属性
例如,如果$qtype=truefalse
我需要为对象自动将动态属性设置为truefalse=true。使用附加变量分两步执行:
Fatal error</b>: Cannot access empty property in QuestionVO
显然,$methodname
必须已填充,因此如果将其传递到构造函数中可能会更好:
class QuestionVO {
public $qtype;
function __construct() {
$methodname = $this->qtype;
$this->$methodname = true;
}
您有以下代码
class QuestionVO {
public $qtype;
function __construct($methodname) {
$this->qtype = $methodname;
$this->$methodname = true;
}
这里,get\u class(new QuestionVO())
您将一个对象作为参数传递给了get\u class
方法,因此,请这样想:
$statement->setFetchMode(\PDO::FETCH_CLASS, get_class(new QuestionVO()));
$obj=new QuestionVO();// PDO确实会在调用构造函数之前填充对象。但是,当您简单地调用newquestionvo
时,它不会填充对象
因此,使用get_类(new QuestionVO())
是行不通的,而且您也不需要这样做。只需命名类,如下所示:
$obj = new QuestionVO(); // <-- error is rising at this point of initialization
get_class($obj);
但是,如果查询结果集中的qtype
的值为null,会发生什么情况?然后你又回到了同样的问题上
您应该将构造函数编码为不假定设置了qtype
:
$statement->setFetchMode(\PDO::FETCH_CLASS, 'QuestionVO');
首先设置$this->qtype
的值。那么$qtype
永远不会是的“truefalse”
,对吗?它的默认值可能是null
。这个类是在设置$qtype
的地方继承的吗?我已经编辑了我的问题,属性是由PDO在调用构造函数之前设置的\n如果属性是由PDO设置的,我已经修改了问题,那么它应该是可以的,因为PDO
在调用构造函数之前填充您的实例。请先尝试第一个代码段,如果没有帮助的话,再尝试另一个。另外:在设置动态属性之前和之后,请尝试在构造函数中执行var_转储(this)。同样的错误是,无法访问中的空属性(我无法传递构造函数,因为它由PDO调用)尝试了var_转储($this),但所有属性都显示为NULL,echo$this->qtype显示有效值
$statement->setFetchMode(\PDO::FETCH_CLASS, 'QuestionVO');
function __construct() {
if (isset($this->qtype)) {
$this->{$this->qtype} = true;
}
}