Objects\createWith()

higher-order transformer returns Closure
(class-string, map) → (map → C)
At a glance — Partial-application for object construction. The Closure merges your overrides over the base properties every time it is called. Returns a fresh object on every call.

Creates a factory Closure that instantiates a class with a merged set of base properties and per-call overrides. Works well as a fixture builder or prototype factory.

/**
  * @param class-string $class
  * @param array<string, mixed> $baseProperties
  * @return Closure(array<string, mixed>):object
  */
Objects\createWith(string $class, array $baseProperties = []): Closure

Returned Closure

When Objects\createWith() is called, it returns the following Closure which can be used like a regular function.

/**
  * @param array<string, mixed> $overrides
  * @return object An instance of the bound class.
  */
$function (array $overrides): object

Examples

Partial Application

This can be used to create a simple closure which can be used as a regular function.

class User {
  public string $name = '';
  public string $role = 'user';
  public bool   $active = true;
}

// A fixture builder for tests — every User starts active with role 'user'.
$makeUser = Objects\createWith(User::class, ['role' => 'user', 'active' => true]);

$admin  = $makeUser(['name' => 'Ada', 'role' => 'admin']);
$member = $makeUser(['name' => 'Bea']);   // inherits role=user, active=true

var_dump($admin->role);   // 'admin' — overridden
var_dump($member->role);  // 'user'  — from base

Curried

This can be called inline using currying.

$default = Objects\createWith(User::class)(['name' => 'Guest']);
// new User with name='Guest', other defaults from the class itself.

Details

Objects Functions

Releated Construction Functions