我正在尝试生成一个在数据库中提取的对象数组。
我尝试这样做的代码是:
public function findAllObjects() {
$conn = $this->openConnection();
$result = $conn->query('SELECT * FROM content');
while ($content = $result->fetch_object($class = 'Content')) {
var_dump($content);
$contents[] = $content;
}
$conn = $this->closeConection();
return $contents;
}
如果我使用var_dump
,结果如下:
object(Content)[4]
protected 'id_content' => string '1' (length=1)
public 'title' => null
public 'description' => null
public 'category' => null
public 'date' => string '2015-01-01' (length=10)
public 'townReceiver' => null
public 'author' => null
显然,表Content具有全部信息,但此代码仅获取id
和date
。有什么解决这个问题的建议吗?非常感谢。
编辑$class = 'Content'
它是参数class_name
,来自官方文件:
要实例化的类的名称,设置和的属性回来如果未指定,则返回stdClass对象。
您可以在以下网址找到更多信息:
http://php.net/manual/en/mysqli-result.fetch-object.php
这是class
含量的矩阵:
class Content extends Model {
protected $id_content;
public $title;
public $description;
public $category;
public $date;
public $townReceiver;
public $author;
function __construct($title = null, $description = null, $category = null, $townReceiver = null, $author = null) {
$this->title = $title;
$this->description = $description;
$this->category = $category;
$this->townReceiver = $townReceiver;
$this->author = $author;
}
//Methods of the class...
编辑2
问题出在__construct
方法上。如果我删除此方法,fetch_object
可以正常工作原因是什么?我不能将__construct与fetch_object
一起使用吗
编辑3
Ryan Vincent评论道,我发现的解决方案是:
function __construct($title = null, $description = null, $category = null, $townReceiver = null, $author = null) {
if (!isset($this->id_content)) {
$this->title = $title;
$this->description = $description;
$this->category = $category;
$this->townReceiver = $townReceiver;
$this->author = $author;
}
}
最后,问题是对象在调用__construct
方法之前被设置,因此,__construct将对象重写为null,正如所定义的那样。
为了避免这种情况,我检查对象的id是否已设置;2种可能性:
1( 如果我想生成一个新内容并将其存储到DB中,那么id将是null
,因为id在DB中分配了自动递增选项。
2( 如果我想获取对象,就会设置id,并且数据不会被覆盖。
所以解决方案是这段代码:
function __construct($title = null, $description = null, $category = null, $townReceiver = null, $author = null) {
if (!isset($this->id_content)) {
$this->title = $title;
$this->description = $description;
$this->category = $category;
$this->townReceiver = $townReceiver;
$this->author = $author;
}
}