match

(PHP 8)

match 표현식은 값의 ID 확인을 기반으로 평가를 분기합니다. switch 문과 유사하게 match 표현식에는 여러 대안과 비교되는 subject 표현식이 있습니다. match와 달리 삼항 표현식과 매우 유사한 값으로 평가됩니다. match와 달리 비교는 약한 동등성 검사(==)가 아닌 동일성 검사(===)입니다. 일치 표현식은 PHP 8.0.0부터 사용할 수 있습니다.

예제 #1 match 표현식의 구조

                  
<?php
$return_value = match (subject_expression) {
    single_conditional_expression => return_expression,
    conditional_expression1, conditional_expression2 => return_expression,
};
?>
                  
                

예제 #2 기본 match 사용법

                  
<?php
$food = 'cake';

$return_value = match ($food) {
    'apple' => 'This food is an apple',
    'bar' => 'This food is a bar',
    'cake' => 'This food is a cake',
};

var_dump($return_value);
?>
                  
                

위의 예는 다음을 출력합니다.

string(19) "This food is a cake"
                

참고: match 표현식의 결과는 사용할 필요가 없습니다.

참고: match 표현식은 세미콜론 ;으로 끝나야 합니다.

match 표현식은 switch 문과 유사하지만 몇 가지 주요 차이점이 있습니다.

  • match arm은 switch 문처럼 느슨하게가 아니라 엄격하게(===) 값을 비교합니다.
  • match 표현식은 값을 반환합니다.
  • match arm은 switch 문처럼 나중의 경우로 넘어가지 않습니다.
  • match 표현식은 완전해야 합니다.

switch 문으로, match 표현식은 match arm by match arm으로 실행됩니다. 처음에는 코드가 실행되지 않습니다. 조건식은 이전의 모든 조건식이 주제 표현식과 일치하지 않는 경우에만 평가됩니다. 일치하는 조건식에 해당하는 반환 식만 평가됩니다. 예를 들어:

                  
<?php
$result = match ($x) {
    foo() => ...,
    $this->bar() => ..., // $this->bar() isn't called if foo() === $x
    $this->baz => beep(), // beep() isn't called unless $x === $this->baz
    // etc.
};
?>
                  
                

match 표현식 팔은 쉼표로 구분된 여러 표현식을 포함할 수 있습니다. 이것은 논리적 OR이고 오른쪽이 동일한 여러 매치 암의 약어입니다.

                  
<?php
$result = match ($x) {
    // This match arm:
    $a, $b, $c => 5,
    // Is equivalent to these three match arms:
    $a => 5,
    $b => 5,
    $c => 5,
};
?>
                  
                

특별한 경우가 default 패턴입니다. 이 패턴은 이전에 일치하지 않은 모든 항목과 일치합니다. 예를 들어:

                  
<?php
$expressionResult = match ($condition) {
    1, 2 => foo(),
    3, 4 => bar(),
    default => baz(),
};
?>
                  
                

참고: 여러 기본 패턴은 E_FATAL_ERROR 오류를 발생시킵니다.

match 표현식은 완전해야 합니다. 주제 표현식이 매치 암에 의해 처리되지 않으면 UnhandledMatchError가 발생합니다.

예제 #3 처리되지 않은 일치 표현식의 예

                  
<?php
$condition = 5;

try {
    match ($condition) {
        1, 2 => foo(),
        3, 4 => bar(),
    };
} catch (\UnhandledMatchError $e) {
    var_dump($e);
}
?>
                  
                

위의 예는 다음을 출력합니다.

object(UnhandledMatchError)#1 (7) {
  ["message":protected]=>
  string(33) "Unhandled match value of type int"
  ["string":"Error":private]=>
  string(0) ""
  ["code":protected]=>
  int(0)
  ["file":protected]=>
  string(9) "/in/ICgGK"
  ["line":protected]=>
  int(6)
  ["trace":"Error":private]=>
  array(0) {
  }
  ["previous":"Error":private]=>
  NULL
}
                
match 표현식을 사용하여 비 신원 확인 처리

true를 주제 표현식으로 사용하여 일치 표현식을 사용하여 ID가 ​​아닌 조건부 케이스를 처리할 수 있습니다.

예제 #4 일반화된 match 표현식을 사용하여 정수 범위에서 분기

                  
<?php

$age = 23;

$result = match (true) {
    $age >= 65 => 'senior',
    $age >= 25 => 'adult',
    $age >= 18 => 'young adult',
    default => 'kid',
};

var_dump($result);
?>
                  
                

위의 예는 다음을 출력합니다.

string(11) "young adult"
                

예제 #5 일반화된 일치 표현식을 사용하여 문자열 콘텐츠에서 분기

                  
<?php

$text = 'Bienvenue chez nous';

$result = match (true) {
    str_contains($text, 'Welcome') || str_contains($text, 'Hello') => 'en',
    str_contains($text, 'Bienvenue') || str_contains($text, 'Bonjour') => 'fr',
    // ...
};

var_dump($result);
?>
                  
                

위의 예는 다음을 출력합니다.

string(2) "fr"