Last active
February 5, 2018 15:20
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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