My main question is if there is support for object properties in PDO?
I'm looking to go straight from my sql results to the User class. I know I can create an interpreter-type class but I was hoping for a straightforward solution. Can anyone help, please?
The error is as follows:
Typed property User::$DateCreated must be an instance of DateTime, string used
This is my php class
class User
{
public int $UserId;
public string $Username;
public string $Email;
public string $PassHash;
public DateTime $DateCreated; // problem area
public bool $Active;
}
And this is how it looks in the db
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 | |
+-------------+--------------+------+-----+-------------------+----------------+
I'm calling it with this function, which is breaking because it's trying to push a string in into a DateTime property
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");
}
However, when I run this code, it returns a DateTime object, just like you'd expect.
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
}