class Instantiator

A utility class to create objects without calling their constructor.

Methods

static object
instantiate(string $class, array $properties = array(), array $privateProperties = array())

Creates an object and sets its properties without calling its constructor nor any other methods.

Details

static object instantiate(string $class, array $properties = array(), array $privateProperties = array())

Creates an object and sets its properties without calling its constructor nor any other methods.

For example:

// creates an empty instance of Foo
Instantiator::instantiate(Foo::class);

// creates a Foo instance and sets one of its properties
Instantiator::instantiate(Foo::class, ['propertyName' => $propertyValue]);

// creates a Foo instance and sets a private property defined on its parent Bar class
Instantiator::instantiate(Foo::class, [], [
    Bar::class => ['privateBarProperty' => $propertyValue],
]);

Instances of ArrayObject, ArrayIterator and SplObjectHash can be created by using the special "\0" property name to define their internal value:

// creates an SplObjectHash where $info1 is attached to $obj1, etc.
Instantiator::instantiate(SplObjectStorage::class, ["\0" => [$obj1, $info1, $obj2, $info2...]]);

// creates an ArrayObject populated with $inputArray
Instantiator::instantiate(ArrayObject::class, ["\0" => [$inputArray]]);

Parameters

string $class The class of the instance to create
array $properties The properties to set on the instance
array $privateProperties The private properties to set on the instance, keyed by their declaring class

Return Value

object The created instance

Exceptions

ExceptionInterface When the instance cannot be created