Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class B
- {
- public $id = 123;
- }
- class C
- {
- private $values = [1, 2, 3];
- private $ident = 'abc';
- }
- class A
- {
- private $b;
- public $c;
- private $age = 42;
- private $name = 'Foo';
- public function __construct(B $b)
- {
- $this->b = $b;
- }
- }
- class D
- {
- public $name = 'Test';
- private $age = 42;
- }
- $a = new A(new B());
- $a->c = new C();
- $d = new D();
- //print serialize($d);
- function serialized(stdClass $std, string $class): string
- {
- return sprintf(
- 'O:%d:"%s"%s',
- strlen($class),
- $class,
- strstr(strstr(serialize($std), '"'), ':')
- );
- }
- function cast(stdClass $std, string $class, array $properties = [])
- {
- foreach($std as $key => $prop) {
- if ($prop instanceof stdClass) {
- $std->{$key} = cast($prop, $properties[$key]);
- }
- }
- $serialized = preg_replace(
- '/^O:\d+:"[^"]++"/',
- 'O:' . strlen($class) . ':"' . $class . '"',
- serialize($std)
- );
- if ($class === A::class) {
- print_r($serialized);
- exit;
- }
- return unserialize($serialized);
- }
- var_dump($d);
- var_dump($a);
- print '====' . PHP_EOL;
- $std1 = json_decode('{"name":"Test"}');
- var_dump(cast($std1, D::class));
- $std2 = json_decode('{"b":{"id":123},"c":{"values":[1,2,3],"ident":"abc"},"age":42,"name":"Foo"}');
- var_dump(cast($std2, A::class, ['b' => B::class, 'c' => C::class]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement