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 = []): ClosureWhen 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): objectThis 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 baseThis can be called inline using currying.
$default = Objects\createWith(User::class)(['name' => 'Guest']);
// new User with name='Guest', other defaults from the class itself.