Skip to content

Instantly share code, notes, and snippets.

@henriquemoody
Last active December 8, 2018 18:54
Show Gist options
  • Save henriquemoody/3e9d2b253a2502bbb20552ddc683cd76 to your computer and use it in GitHub Desktop.
Save henriquemoody/3e9d2b253a2502bbb20552ddc683cd76 to your computer and use it in GitHub Desktop.
<?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
// )
@wesleyvicthor
Copy link

maybe a better api for that would have only $from and $to and get the class with get_class, so you can avoid covertObject(new Duck(), Moody::class, Cow::class)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment