Created
April 22, 2013 08:30
-
-
Save dazz/5433273 to your computer and use it in GitHub Desktop.
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 | |
/** | |
* Class casting | |
* | |
* @param string|object $destination | |
* @param object $sourceObject | |
* @return object | |
*/ | |
function cast_long($destination, $sourceObject) | |
{ | |
if (is_string($destination)) { | |
$destination = new $destination(); | |
} | |
$sourceReflection = new ReflectionObject($sourceObject); | |
$destinationReflection = new ReflectionObject($destination); | |
$sourceProperties = $sourceReflection->getProperties(); | |
foreach ($sourceProperties as $sourceProperty) { | |
$sourceProperty->setAccessible(true); | |
$name = $sourceProperty->getName(); | |
$value = $sourceProperty->getValue($sourceObject); | |
if ($destinationReflection->hasProperty($name)) { | |
$propDest = $destinationReflection->getProperty($name); | |
$propDest->setAccessible(true); | |
$propDest->setValue($destination,$value); | |
} else { | |
$destination->$name = $value; | |
} | |
} | |
return $destination; | |
} | |
function objectToObject($instance, $className) { | |
return unserialize(sprintf( | |
'O:%d:"%s"%s', | |
strlen($className), | |
$className, | |
strstr(strstr(serialize($instance), '"'), ':') | |
)); | |
} | |
function cast_hack($to_class, $obj) { | |
if(class_exists($to_class)) { | |
$obj_in = serialize($obj); | |
var_dump($obj_in); | |
$obj_out = 'O:' . strlen($to_class) . ':"' . $to_class . '":' . substr($obj_in, $obj_in[2] + 7); | |
var_dump($obj_out); | |
return unserialize($obj_out); | |
} | |
return false; | |
} | |
function cast($destination, \stdClass $source) | |
{ | |
$sourceReflection = new \ReflectionObject($source); | |
$sourceProperties = $sourceReflection->getProperties(); | |
foreach ($sourceProperties as $sourceProperty) { | |
$name = $sourceProperty->getName(); | |
$destination->{$name} = $source->$name; | |
} | |
return $destination; | |
} | |
class Test { | |
public $test = 1; | |
public function __construct() { | |
echo __FUNCTION__; | |
} | |
} | |
$toCast = new \stdClass(); | |
$toCast->test = 2; | |
$toCast->otherValue = "test"; | |
$toCast->nestedObject = new \stdClass(); | |
$toCast->nestedObject->value = 1; | |
var_dump(microtime(), $toCast); | |
$casted = cast(new Test, $toCast); | |
var_dump(microtime(), $casted); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment