Skip to content

Instantly share code, notes, and snippets.

@gooh
Last active December 13, 2015 18:39
Show Gist options
  • Save gooh/4957162 to your computer and use it in GitHub Desktop.
Save gooh/4957162 to your computer and use it in GitHub Desktop.
Here be dragons and black magic!
<?php
class Caster
{
/**
* Casts an Array to an instance of a class
*
* This method will return an instance of the given $className with all
* elements in the array being public members of the instance. The method
* uses serialization to work, so no constructor will be called to get the
* instance of $className. The returned instance may behave unexpectedly
* when the array contains values that are non-public members in the class.
*
* @param array $array
* @param string $className
* @return Mixed an instance of $className
*/
public static function arrayToObject(array $array, $className)
{
if (!is_string($className)) {
throw new \InvalidArgumentException('Argument 2 must be a String');
}
return unserialize(
sprintf(
'O:%d:"%s"%s',
strlen($className),
$className,
strstr(serialize($array), ':')
)
);
}
/**
* Casts any object instance to a different class
*
* This method will cast the object instance passed to it an instance of
* the class given as the second argument. If any of the arguments is not
* of the expected type, the method will throw an InvalidArgument Exception.
* The method uses serialization to work, so no constructor will be called
* to cast the instance of $className. This might put the new instance into
* an invalid state.
*
* @throws \InvalidArgumentException
* @param Object $instance
* @param String $className
* @return Mixed an instance of $className
*/
public static function castToObject($instance, $className)
{
if (!is_object($instance)) {
throw new \InvalidArgumentException(
'Argument 1 must be an Object'
);
}
if (!class_exists($className)) {
throw new \InvalidArgumentException(
'Argument 2 must be an existing Class'
);
}
return unserialize(
sprintf(
'O:%d:"%s"%s',
strlen($className),
$className,
strstr(strstr(serialize($instance), '"'), ':')
)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment