Created
October 7, 2024 10:25
-
-
Save whchi/20a336551510bf6846779db5c61cd1ed to your computer and use it in GitHub Desktop.
php dto example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class BaseDto | |
| { | |
| /** | |
| * Constructor that dynamically sets properties based on the given associative array | |
| * | |
| * @param array $data The data to be used for setting properties | |
| */ | |
| public function __construct(array $data) | |
| { | |
| foreach ($data as $key => $value) { | |
| $this->{$key} = $value; | |
| } | |
| } | |
| /** | |
| * Magic method to handle getting properties dynamically | |
| * | |
| * @param string $name The name of the property to get | |
| * @return mixed|null The value of the property if it exists, or null otherwise | |
| */ | |
| public function __get(string $name) | |
| { | |
| return $this->{$name} ?? null; | |
| } | |
| /** | |
| * Magic method to handle setting properties dynamically | |
| * | |
| * @param string $name The name of the property to set | |
| * @param mixed $value The value to set the property to | |
| */ | |
| public function __set(string $name, $value): void | |
| { | |
| $this->{$name} = $value; | |
| } | |
| } | |
| class UserDto extends BaseDto | |
| { | |
| public string $name; | |
| public string $email; | |
| } | |
| // Usage example | |
| $userData = [ | |
| 'email' => 'john.doe@example.com', | |
| 'name' => 'John Doe', | |
| ]; | |
| $user = new UserDto($userData); | |
| // Accessing properties | |
| echo $user->name; // Output: John Doe | |
| echo $user->email; // Output: john.doe@example.com |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment