Documentation

Instantiator
in package

A utility class to create objects without calling their constructor.

Tags
author

Nicolas Grekas p@tchwork.com

Table of Contents

instantiate()  : object
Creates an object and sets its properties without calling its constructor nor any other methods.

Methods

instantiate()

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

public static instantiate(string $class[, array<string|int, mixed> $properties = [] ][, array<string|int, mixed> $privateProperties = [] ]) : object

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 SplObjectStorage can be created by using the special "\0" property name to define their internal value:

// creates an SplObjectStorage 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
$class : string

The class of the instance to create

$properties : array<string|int, mixed> = []

The properties to set on the instance

$privateProperties : array<string|int, mixed> = []

The private properties to set on the instance, keyed by their declaring class

Tags
throws
ExceptionInterface

When the instance cannot be created

Return values
object

Search results