Since the enum feature was released in PHP8.1, I was wondering how can I fetch data from my database with PDO into an object with an ENUM property.
I have the following enum:
enum UserType{
case Master: 1;
case Admin: 2;
case Manager: 3;
}
And I have the following class:
class User{
private int $id;
private string $name;
private UserType $userType;
}
Every time I try to execute the code below I get the error Cannot assign int to property User::$userType of type UserType
Database::getInstance()->fetchObject(sql: "SELECT id, name, userType FROM user WHERE id = 1", class_name: User::class);
I want to know if there is a way to make the code above works or what is the best way to implement the new enum feature in my code.
My fetchObject code:
public function fetchObject($sql, array $args = array(), string $class_name = "stdClass"): mixed
{
$sql = self::$instance->prepare($sql);
if(empty($args)){
$sql->execute();
} else{
$sql->execute($args);
}
$object = $sql->fetchObject($class_name);
$sql->closeCursor();
return $object;
}