Created
February 2, 2022 13:55
-
-
Save webdevilopers/6641aeebb410aa7aad2a5c00813f8c2e to your computer and use it in GitHub Desktop.
Automatically populate PHP object from Array
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 declare(strict_types=1); | |
namespace Acme\Shared\Application\Service; | |
trait PayloadMessage | |
{ | |
private function __construct() | |
{} | |
/** | |
* @param array $payload | |
* | |
* @return static | |
* @todo Return static. | |
* @see https://stitcher.io/blog/php-8-before-and-after#static-instead-of-doc-blocks | |
*/ | |
public static function fromPayload(array $payload) | |
{ | |
$self = new static(); | |
foreach (get_class_vars(get_class($self)) as $varName => $varValue) { | |
if (array_key_exists($varName, $payload)) { | |
$self->$varName = $payload[$varName]; | |
} | |
} | |
return $self; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The current solution does not work e.g. for arrays.
Cannot assign string to property AddPerson::$biographicInformation of type array