Skip to content

Instantly share code, notes, and snippets.

@olvlvl
Created August 23, 2011 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save olvlvl/1166786 to your computer and use it in GitHub Desktop.
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
<?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