【发布时间】:2020-11-08 03:23:59
【问题描述】:
我的主要问题是 PDO 中是否支持对象属性?
我希望直接从我的 sql 结果转到 User 类。我知道我可以创建一个解释器类型的类,但我希望有一个简单的解决方案。有人可以帮忙吗?
错误如下:
Typed property User::$DateCreated must be an instance of DateTime, string used
这是我的 php 类
class User
{
public int $UserId;
public string $Username;
public string $Email;
public string $PassHash;
public DateTime $DateCreated; // problem area
public bool $Active;
}
这就是它在数据库中的样子
mysql> desc Users;
+-------------+--------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+-------------------+----------------+
| UserId | int(11) | NO | PRI | NULL | auto_increment |
| Username | varchar(30) | YES | | NULL | |
| Email | varchar(200) | YES | | NULL | |
| PassHash | varchar(250) | YES | | NULL | |
| DateCreated | datetime | YES | | CURRENT_TIMESTAMP | |
| Active | tinyint(1) | YES | | 0 | |
+-------------+--------------+------+-----+-------------------+----------------+
我正在用这个函数调用它,因为它试图将一个字符串推入 DateTime 属性,所以它正在中断
public function GetUsers() : array
{
$sql = "SELECT UserId, Username, Email, DateCreated, Active FROM Users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_CLASS, "User");
}
但是,当我运行此代码时,它会返回一个 DateTime 对象,正如您所期望的那样。
public function GetUsersThisWorksTho() : array
{
$sql = "SELECT DateCreated FROM Users";
$stmt = $this->db->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_CLASS, "DateTime");
// this works. It actually casts the result as a php DateTime object
}
【问题讨论】:
-
经过快速调查,discovered that SQL Server 有一个 PDO 属性
PDO::SQLSRV_ATTR_FETCHES_DATETIME_TYPE。不幸的是,这似乎不适用于 MySQL PDO 驱动程序。很好奇 DateTime 独奏查询是否按预期进行。找不到任何文档解释为什么会发生这种情况。 o_O