Oihana PHP System

HydrateWith

Specifies the class to use when hydrating each element of an array property.

This attribute is used by the Reflection::hydrate() method to determine the class to instantiate for each element in an array when the property type is simply array or the type hint lacks precision.

It is particularly useful for collections of objects where the target class cannot be inferred directly from the property type or PHPDoc.

Tags
example

Hydrate an array of objects

class Comment
{
    public string $text;
}

class Post
{
    #[HydrateWith(Comment::class)]
    public array $comments;
}

$data = ['comments' => [['text' => 'Hello'], ['text' => 'World']]];
$post = (new Reflection())->hydrate($data, Post::class);
echo $post->comments[1]->text; // "World"

Hydrate an array of DTOs when type is ambiguous

class Metric
{
    public string $label;
}

class Dashboard
{
    /** @var Metric *\/
    #[HydrateWith(Metric::class)]
    public array $metrics;
}
author

Marc Alcaraz

since
1.0.0
Attributes
#[Attribute]
\Attribute::TARGET_PROPERTY

Table of Contents

Properties

$classes  : array<string|int, mixed>

Methods

__construct()  : mixed

Properties

Methods

__construct()

public __construct(mixed ...$classes) : mixed
Parameters
$classes : mixed

        
On this page

Search results