Created
August 23, 2011 22:33
-
-
Save olvlvl/1166786 to your computer and use it in GitHub Desktop.
Create an instance in the same fashion as PDO with the FETCH_CLASS mode
This file contains 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 instantiate($class_name, array $properties=array(), array $construct_args=array()) | |
{ | |
$class_reflection = new \ReflectionClass($class_name); | |
$properties_count = 0; | |
$serialized = ''; | |
if ($properties) | |
{ | |
$class_reflection = new \ReflectionClass($class_name); | |
$class_properties = $class_reflection->getProperties(); | |
$defaults = $class_reflection->getDefaultProperties(); | |
$done = array(); | |
foreach ($class_properties as $property) | |
{ | |
if ($property->isStatic()) | |
{ | |
continue; | |
} | |
$properties_count++; | |
$identifier = $property->name; | |
$done[] = $identifier; | |
$value = null; | |
if (array_key_exists($identifier, $properties)) | |
{ | |
$value = $properties[$identifier]; | |
} | |
else if (isset($defaults[$identifier])) | |
{ | |
$value = $defaults[$identifier]; | |
} | |
if ($property->isProtected()) | |
{ | |
$identifier = "\x00*\x00" . $identifier; | |
} | |
else if ($property->isPrivate()) | |
{ | |
$identifier = "\x00" . $property->class . "\x00" . $identifier; | |
} | |
$serialized .= serialize($identifier) . serialize($value); | |
} | |
$extra = array_diff(array_keys($properties), $done); | |
foreach ($extra as $name) | |
{ | |
$properties_count++; | |
$serialized .= serialize($name) . serialize($properties[$name]); | |
} | |
} | |
$serialized = 'O:' . strlen($class_name) . ':"' . $class_name . '":' . $properties_count . ':{' . $serialized . '}'; | |
$instance = unserialize($serialized); | |
if (method_exists($instance, '__construct')) | |
{ | |
call_user_func_array(array($instance, '__construct'), $construct_args); | |
} | |
return $instance; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment