PHP8's Match Expression Example

Published on Jul 14, 2021

Saw this code on a PHP 7.4 project I'm refactoring:

public function getFriendlyCertificateTypeAttribute()
{
    $certificateType = '';
    switch ($this->type) {
        case Draft::BIRTH:
            $certificateType = 'Certificate of Live Birth';
            break;
        case Draft::MARRIAGE:
            $certificateType = 'Certificate of Marriage';
            break;
        case Draft::CENOMAR:
            $certificateType = 'CENOMAR';
            break;
        case Draft::DEATH:
            $certificateType = 'Certificate of Death';
            break;
    }

    return $certificateType;
}

With PHP 8.0, it becomes much cleaner:

public function getFriendlyCertificateTypeAttribute(): string
{
    return match($this->type) {

        Draft::BIRTH => 'Certificate of Live Birth',

        Draft::MARRIAGE => 'Certificate of Marriage',

        Draft::CENOMAR => 'CENOMAR',

        Draft::DEATH => 'Certificate of Death',

    };
}