3v4l.org

run code in 300+ PHP versions simultaneously
<?php $config = [ 'legendaryName' => [ 'column' => 'legendary_name', 'type' => 'string', ] ]; $data = ['legendary_name' => 'The Hammer']; class Warrior { use DbHydrate; private $legendaryName; } trait DbHydrate { public function extract($config) { $row = []; foreach($config as $attributeName => $attributeConfig) { if(property_exists($this, $attributeName)) { $columnName = $attributeConfig['column']; $row[$columnName] = $this->{$attributeName}; } else { throw new \Exception(sprintf('The property %s does not exists in %s', $attributeName, self::class)); } } return $row; } public function hydrate($config, $data) { foreach($config as $attributeName => $attributeConfig) { if(property_exists($this, $attributeName)) { $columnName = $attributeConfig['column']; $value = $data[$columnName]; if ($attributeConfig['type'] === 'string' && is_string($value)) { $this->{$attributeName} = $value; } } else { throw new \Exception(sprintf('The property %s does not exists in %s', $attributeName, self::class)); } } } } $legendaryWarrior = new Warrior; $legendaryWarrior->hydrate($config, $data); var_dump($legendaryWarrior->extract($config)); var_dump($legendaryWarrior); /* $config = ['classicalName' => 'classical_name']; $data = ['classical_name' => 'John']; $testWarrior = new Warrior; $testWarrior->hydrate($config, $data); var_dump($testWarrior);*/

preferences:
50.52 ms | 402 KiB | 5 Q