- unserialize: documentation ( source)
- print_r: documentation ( source)
- serialize: documentation ( source)
- array_keys: documentation ( source)
- get_object_vars: documentation ( source)
<?php
/**
* Provides dependency injection friendly methods for serialization.
*/
trait DependencySerializationTrait {
/**
* An array of service IDs keyed by property name used for serialization.
*
* @var array
*/
// phpcs:ignore Drupal.Classes.PropertyDeclaration
protected $_serviceIds = [];
/**
* An array of entity type IDs keyed by the property name of their storages.
*
* @var array
*/
// phpcs:ignore Drupal.Classes.PropertyDeclaration
protected $_entityStorages = [];
/**
* {@inheritdoc}
*/
public function __sleep() {
$closure = \Closure::bind(static function ($class) {
return get_object_vars($class);
}, NULL, $this);
$vars = $closure($this);
return array_keys($vars);
}
/**
* {@inheritdoc}
*/
#[\ReturnTypeWillChange]
public function __wakeup() {
}
}
class A {
use DependencySerializationTrait;
private int $a = 1;
public function doIt() {
print "get_object_vars()\n";
print_r(get_object_vars($this));
$closure = \Closure::bind(static function ($class) {
return get_object_vars($class);
}, NULL, $this);
$vars = $closure($this);
print "\n\nClosure\n";
print_r($vars);
}
protected function foo() {
return $this->a;
}
}
class B extends A {
private int $a = 42;
private int $b = 2;
public function bar() {
return $this->foo();
}
public function baz() {
return $this->a;
}
}
$b = new B();
$b->doit();
echo PHP_EOL;
echo "Before serialize:" . PHP_EOL;
echo $b->bar() . PHP_EOL;
echo $b->baz() . PHP_EOL;
$c = unserialize(serialize($b));
echo "After serialize:" . PHP_EOL;
echo $c->bar() . PHP_EOL;
echo $b->baz() . PHP_EOL;