Last active
December 8, 2018 18:54
-
-
Save henriquemoody/3e9d2b253a2502bbb20552ddc683cd76 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 | |
// Based on https://stackoverflow.com/questions/965611/forcing-access-to-php-incomplete-class-object-properties | |
function convertObject($object, string $from, string $to) | |
{ | |
// Serialize | |
$serialized = serialize($object); | |
// Replace the object-type | |
$objectReplaced = preg_replace( | |
'/O:\d+:"'.preg_quote($from).'"/', | |
sprintf('O:%d:"%s"', strlen($to), $to), | |
$serialized | |
); | |
// Replace the object properties | |
$propertiesReplaced = preg_replace_callback( | |
'/:\d+:"\0'.preg_quote($from).'\0([^"]+)"/', | |
function (array $matches) use ($to): string { | |
return sprintf(':%d:"%s"', strlen($to.$matches[1]) + 2, "\0".$to."\0".$matches[1]); | |
}, | |
$objectReplaced | |
); | |
return unserialize($propertiesReplaced); | |
} | |
abstract class Animal | |
{ | |
private $name; | |
public function __construct(string $name) | |
{ | |
$this->name = $name; | |
} | |
} | |
final class Duck extends Animal | |
{ | |
private $sound = 'Quack'; | |
} | |
final class Cow extends Animal | |
{ | |
private $sound = 'Moo'; | |
} | |
$who = convertObject(new Duck('John'), Duck::class, Cow::class); | |
print_r($who); | |
// Cow Object | |
// ( | |
// [sound:Cow:private] => Quack | |
// [name:Animal:private] => John | |
// ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
maybe a better api for that would have only $from and $to and get the class with
get_class
, so you can avoidcovertObject(new Duck(), Moody::class, Cow::class)