PHP legacy project, best way to get an real object from data (db, request, file etc) [closed] - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Thursday, July 27, 2023

PHP legacy project, best way to get an real object from data (db, request, file etc) [closed]

I have a question about real objects in PHP.

I have an array of data

$userData = [
    'id' => 2,
    'name' => 'Joel',
    'email' => 'joel@gmail.com'
];

and I would like to work with an object instance instead. I want to map the array onto User object:

class User
{
    public ?int $id;
    public string $name;
    public string $email;

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }
    
    /**
     * @param string $name
     */
    public function setName(string $name): void
    {
        $this->name = $name;
    }
    
    /**
     * @return string
     */
    public function getEmail(): string
    {
        return $this->email;
    }
    
    /**
     * @param string $email
     */
    public function setEmail(string $email): void
    {
        $this->email = $email;
    }
    
    /**
     * @return int|null
     */
    public function getId(): ?int
    {
        return $this->id;
    }

}

Possible solution: Add the properties into the constructor (in array or one by one).

Are there any other ways in PHP to achieve the same result?



source https://stackoverflow.com/questions/76727769/php-legacy-project-best-way-to-get-an-real-object-from-data-db-request-file

No comments:

Post a Comment