Skip to content

Instantly share code, notes, and snippets.

@donaldsteele
Last active August 28, 2017 04:54
Show Gist options
  • Save donaldsteele/aa12d5cf39e78949644288b70b9e4c0b to your computer and use it in GitHub Desktop.
Save donaldsteele/aa12d5cf39e78949644288b70b9e4c0b to your computer and use it in GitHub Desktop.
php 7 , hydrate a class by passing in an array
<?php
//example class:
class myObject
{
public $property1;
public $property2;
public $property3;
public $property4;
function __construct($objArray)
{
foreach ($objArray as $key => $value) {
if (property_exists($this, $key)) {
$this->{$key} = $value;
}
}
}
}
//usage:
$objArray = ['property1' => 'value1', 'property2' => 'value2', 'property3' => 'value3', 'property4' => 'value4'];
$newObj = new myObject($objArray);
var_dump($newObj);
// output
object(myObject)#1 (4) {
["property1"]=>
string(6) "value1"
["property2"]=>
string(6) "value2"
["property3"]=>
string(6) "value3"
["property4"]=>
string(6) "value4"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment