gpt4 book ai didi

php - 如何从 MySQL 中获取 PHP 对象

转载 作者:行者123 更新时间:2023-11-29 20:33:05 25 4
gpt4 key购买 nike

我正在尝试生成在数据库中获取的对象数组。

我尝试这样做的代码是这样的:

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;
}

如果我使用 foreach 循环内打印“Content”的值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 具有完整的信息,但此代码仅获取 iddate。有什么建议可以解决这个问题吗?谢谢!

编辑
$class = 'Content' 是参数class_name,来自官方文档:

The name of the class to instantiate, set the properties of and return. If not specified, a stdClass object is returned.

您可以在以下位置找到更多信息:

http://php.net/manual/en/mysqli-result.fetch-object.php
这是 class Content 的属性:

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) 如果我想生成一个新内容并将其存储到数据库中,则 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;
}
}

关于php - 如何从 MySQL 中获取 PHP 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38938261/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com