Posts Tagged object

Array to object conversion in PHP

I just wrote this simple function to convert arrays to objects in PHP.
For me it is convenient to have such a function at hand for quickly generating objects.


/*
* @param $class the name of the class that should be instantiated
* @param $array the array with key=>value combinations that is used to create the object
* @return an object of type $class with the values from $array
*/
function a2o( $class, $array ) { return array2object( $class, $array ); }
function array2object( $class, $array )
{
$obj = new $class( );
foreach($array as $key => $value)
$obj->$key = $value;
return $obj;
}

, , , ,

Leave a comment