I don't use PHP5 since most of my code is deployed on servers only running PHP4, so I don't know if there is a function like this in PHP5. My goal was to make a bless() function similar to perl's because I am really lazy and don't like to deal w/ constructors that take lots of arguments. Often times I have an array w/ all the values that can map to instance variables for the class, and a bless($array, $class) would be handy. For example, I just got a row from a table in a database and that row is basically all the instance vars for an object. I haven't tried it for composite objects (objects that contain objects), so its just for simple object graphs. Its in use on a production site so it seems to work ok. Requires PHP 4.2 or later (uses get_class_vars() ).
Let me know what you think or problems you find.
function bless( &$arr, $class ){
// TODO add check version of PHP?
// make sure the php file defining $class is included already!
if( !class_exists($class)){
trigger_error( "Undefined class $class", E_USER_WARNING );
return;
}
// will be an assoc array of instance var names as keys and NULL for all values
// requires PHP >=4.2 to work right
$inst_vars = get_class_vars( $class );
foreach( $arr as $i=>$v ){
$inst_vars[$i]= $v;
}
// the serialized version of an object in PHP 4 looks similar to serialized array
// so get the serialized version of the array first
$serialized = serialize( $inst_vars );
$serialized = preg_replace( "/^a\:\d+\:/", '', $serialized );
// now add what we need to make this look like serialized object
$serialized = 'O:' . strlen($class) .':"'. strtolower($class) .'":'. count($inst_vars) .':'. $serialized;
// try to unserialize and check if value is FALSE
$obj = unserialize( $serialized );
if( $obj === false ){
trigger_error( "Unable to bless into $class", E_USER_WARNING );
return null;
}
return $obj;
}