Skip to content

Instantly share code, notes, and snippets.

@mykeels
Last active February 5, 2018 15:20
Show Gist options
  • Select an option

  • Save mykeels/ebf874063150a8bddabe3726ec37d594 to your computer and use it in GitHub Desktop.

Select an option

Save mykeels/ebf874063150a8bddabe3726ec37d594 to your computer and use it in GitHub Desktop.
Cast an associative array or object in PHP to an instance of a class (uses a Laravel helper method)
<?php
function cast($object, $class) {
if( !is_object($object) )
throw new InvalidArgumentException('$object must be an object.');
if( !is_string($class) )
throw new InvalidArgumentException('$class must be a string.');
if( !class_exists($class) )
throw new InvalidArgumentException(sprintf('Unknown class: %s.', $class));
$ret = app($class);
foreach (get_object_vars($object) as $key => $value) {
$ret[$key] = $value;
}
return $ret;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment