【问题标题】:Typed property User::$DateCreated must be an instance of DateTime, string used类型化属性 User::$DateCreated 必须是 DateTime 的实例,使用字符串
【发布时间】: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

标签: php pdo php-7


【解决方案1】:

似乎 PDO 不能动态转换对象。

与fetchAll() 一样,构造函数在填充类属性后执行,如果DateCreated 属性是字符串,则可以在构造函数中检查,这样您就可以使用DateTime::CreateFromFormat() 转换为DateTime 对象。

【讨论】:

    【解决方案2】:

    您似乎想要的是Object Relational Mapper (ORM),其中存在一些公开可用的 PHP 库。 Doctrine 很受欢迎。

    【讨论】:

      猜你喜欢
      • 2020-07-23
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多