Skip to content

Instantly share code, notes, and snippets.

@beberlei
Created April 16, 2020 07:17
Show Gist options
  • Save beberlei/050a321cad0294a0ade75ac9da7519b0 to your computer and use it in GitHub Desktop.
Save beberlei/050a321cad0294a0ade75ac9da7519b0 to your computer and use it in GitHub Desktop.
<?php
abstract class Struct
{
public static function fromArray(array $data)
{
$reflection = new ReflectionClass(get_called_class());
$ctor = $reflection->getConstructor();
$params = [];
foreach ($ctor->getParameters() as $parameter) {
$params[] = $data[$parameter->getName()] ?? null;
}
return $reflection->newInstance(...$params);
}
}
class Server extends Struct
{
public function __construct(
public int $id,
public string $name,
public bool $active)
{
}
}
$server = Server::fromArray($row);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment