연산자 우선 순위

연산자의 우선 순위는 두 식을 함께 "단단하게" 묶는 정도를 지정합니다. 예를 들어, 1 + 5 * 3 표현식에서 곱하기("*") 연산자가 더하기("+") 연산자보다 우선 순위가 높기 때문에 답은 18이 아니라 16입니다. 필요한 경우 괄호를 사용하여 우선 순위를 지정할 수 있습니다. 예: (1 + 5) * 318로 평가됩니다.

연산자의 우선 순위가 같으면 연산자의 연관성에 따라 연산자가 그룹화되는 방식이 결정됩니다. 예를 들어 "-"는 왼쪽 연관이므로 1 - 2 - 3(1 - 2) - 3으로 그룹화되고 -4로 평가됩니다. 반면에 "="는 오른쪽 결합이므로 $a = $b = $c$a = ($b = $c)로 그룹화됩니다.

비연관적이고 우선순위가 같은 연산자는 나란히 사용할 수 없습니다. 예를 들어 1 < 2 > 1은 PHP에서 불법입니다. 반면에 == 연산자는 <= 연산자보다 우선 순위가 낮기 때문에 표현식 1 <= 1 == 1은 유효합니다.

연관성은 이항(및 삼항) 연산자에만 의미가 있습니다. 단항 연산자는 접두사 또는 접미사이므로 이 개념을 적용할 수 없습니다. 예를 들어 !!$a!(!$a)로만 그룹화할 수 있습니다.

꼭 필요한 것은 아니지만 괄호를 사용하면 암시적 연산자 우선 순위 및 연관성에 의존하기보다 그룹을 명시적으로 만들어 코드의 가독성을 높일 수 있습니다.

다음 표에는 우선 순위가 가장 높은 연산자가 맨 위에 오도록 연산자가 나열되어 있습니다. 같은 줄에 있는 연산자는 우선 순위가 같으며 이 경우 연관성이 그룹화를 결정합니다.

연산자 우선 순위

Associativity Operators Additional Information
(n/a) clone new clone and new
right ** arithmetic
(n/a) + - ++ -- ~ (int) (float) (string) (array) (object) (bool) @ arithmetic (unary + and -), increment/decrement, bitwise, type casting and error control
left instanceof type
(n/a) ! logical
left * / % arithmetic
left + - . arithmetic (binary + and -), array and string (. prior to PHP 8.0.0)
left << >> bitwise
left . string (as of PHP 8.0.0)
non-associative < <= > >= comparison
non-associative == != === !== <> <=> comparison
left & bitwise and references
left ^ bitwise
left | bitwise
left && logical
left || logical
right ?? null coalescing
non-associative ? : ternary (left-associative prior to PHP 8.0.0)
right = += -= *= **= /= .= %= &= |= ^= <<= >>= ??= assignment
(n/a) yield from yield from
(n/a) yield yield
(n/a) print print
left and logical
left xor logical
left or logical

예제 #1 연관성

                  
<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
// ternary operator associativity differs from C/C++
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2 (prior to PHP 8.0.0)

$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>
                  
                

연산자 우선 순위 및 연관성은 식을 그룹화하는 방법만 결정하며 평가 순서를 지정하지 않습니다. PHP는 (일반적으로) 표현식이 평가되는 순서를 지정하지 않으며 특정 평가 순서를 가정하는 코드는 피해야 합니다. PHP 버전 간에 또는 주변 코드에 따라 동작이 변경될 수 있기 때문입니다.

예제 #2 정의되지 않은 평가 순서

                  
<?php
$a = 1;
echo $a + $a++; // may print either 2 or 3

$i = 1;
$array[$i] = $i++; // may set either index 1 or 2
?>
                  
                

예제 #3 +, -. 동일한 우선 순위를 갖습니다(PHP 8.0.0 이전)

                  
<?php
$x = 4;
// this line might result in unexpected output:
echo "x minus one equals " . $x-1 . ", or so I hope\n";
// because it is evaluated like this line (prior to PHP 8.0.0):
echo (("x minus one equals " . $x) - 1) . ", or so I hope\n";
// the desired precedence can be enforced by using parentheses:
echo "x minus one equals " . ($x-1) . ", or so I hope\n";
?>
                  
                

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

-1, or so I hope
-1, or so I hope
x minus one equals 3, or so I hope
                

메모: =는 대부분의 다른 연산자보다 우선 순위가 낮지만 PHP는 다음과 유사한 표현식을 계속 허용합니다. if (!$a = foo()), 이 경우 foo()의 반환 값은 $a에 넣습니다.

변경 로그
Version Description
8.0.0 String concatenation (.) now has a lower precedence than arithmetic addition/subtraction (+ and -) and bitwise shift left/right (<< and >>); previously it had the same precedence as + and - and a higher precedence than << and >>.
8.0.0 The ternary operator (? :) is non-associative now; previously it was left-associative.
7.4.0 Relying on the precedence of string concatenation (.) relative to arithmetic addition/subtraction (+ or -) or bitwise shift left/right (<< or >>), i.e. using them together in an unparenthesized expression, is deprecated.
7.4.0 삼항 연산자(? :)의 왼쪽 결합성에 의존하는 것, 즉 괄호로 묶지 않은 여러 삼항 연산자를 중첩하는 것은 더 이상 사용되지 않습니다.