( - the function call operator - has higher precedence than ++ and --, but lower precedence than [.
Therefore you can do the following:
<?php
$func[0] = 'exit';
$func[0]();
?>
But the following will cause a syntax error:
<?php
function func() {
return array('string');
}
func()[0];
?>
연산자 우선권
연산자 우선권은 두 표현이 얼마나 "단단하게" 묶여 있는지 정의합니다. 예를 들어, 1 + 5 * 3 표현의 답은 18이 아닌 16입니다. 곱셈("*") 연산자가 덧셈(+) 연산자보다 높은 우선권을 가지기 때문입니다. 필요하다면, 우선권을 강제하기 위해 괄호를 사용할 수 있습니다. 예를 들면: (1 + 5) * 3은 18로 평가됩니다. 연산자 우선권이 같으면, 왼쪽에서 오른쪽 결합을 사용합니다.
다음 표는 높은 우선권을 가지는 연산자가 위쪽에 나오는 연산자 우선권 목록입니다. 같은 줄에 있는 연산자는 같은 우선권을 가지며, 이 경우 결합이 평가하는 순서를 결정합니다.
| 결합 | 연산자 | 추가 정보 |
|---|---|---|
| 무결합 | clone new | clone과 new |
| 왼쪽 | [ | array() |
| 무결합 | ++ -- | 증가/감소 |
| 무결합 | ~ - (int) (float) (string) (array) (object) (bool) @ | 자료형 |
| 무결합 | instanceof | 자료형 |
| 오른쪽 | ! | 논리 |
| 왼쪽 | * / % | 계산 |
| 왼쪽 | + - . | 계산 그리고 문자열 |
| 왼쪽 | << >> | 비트 |
| 무결합 | < <= > >= <> | 비교 |
| 무결합 | == != === !== | 비교 |
| 왼쪽 | & | 비트 그리고 참조 |
| 왼쪽 | ^ | 비트 |
| 왼쪽 | | | 비트 |
| 왼쪽 | && | 논리 |
| 왼쪽 | || | 논리 |
| 왼쪽 | ? : | 삼항 |
| 오른쪽 | = += -= *= /= .= %= &= |= ^= <<= >>= | 할당 |
| 왼쪽 | and | 논리 |
| 왼쪽 | xor | 논리 |
| 왼쪽 | or | 논리 |
| 왼쪽 | , | 다양한 사용 |
왼쪽 결합은 표현이 왼쪽에서 오른쪽으로 평가됨을 의미하며, 오른쪽 결합은 반대입니다.
Example #1 결합성
<?php
$a = 3 * 3 % 5; // (3 * 3) % 5 = 4
$a = true ? 0 : true ? 1 : 2; // (true ? 0 : true) ? 1 : 2 = 2
$a = 1;
$b = 2;
$a = $b += 3; // $a = ($b += 3) -> $a = 5, $b = 5
?>
Note:
=이 대부분의 연산자보다 낮은 우선권을 가지지만, PHP는 다음과 같은 표현을 허용합니다: if (!$a = foo()), 이 경우 foo()의 반환값은 $a에 들어갑니다.
Christopher Schramm
02-Jul-2011 09:29
charles at pilger dot com dot br
09-Feb-2011 12:00
Be very careful with the precedence. See this code:
<?php
$a = 1;
$b = null;
$c = isset($a) && isset($b);
$d = ( isset($a) and isset($b) );
$e = isset($a) and isset($b);
var_dump($a, $b, $c, $d, $e);
?>
Result:
int(1)
NULL
bool(false)
bool(false)
bool(true) <==
kiamlaluno at avpnet dot org
12-Jul-2010 04:41
Be careful of the difference between
<?php
$obj = new class::$staticVariable();
?>
<?php
$value = class::$staticVariable();
?>
In the first case, the object class will depend on the static variable class::$staticVariable, while in the second case it will be invoked the method whose name is contained in the variable $staticVariable.
headden at karelia dot ru
09-Jun-2009 04:02
Although example above already shows it, I'd like to explicitly state that ?: associativity DIFFERS from that of C++. I.e. convenient switch/case-like expressions of the form
$i==1 ? "one" :
$i==2 ? "two" :
$i==3 ? "three" :
"error";
will not work in PHP as expected
Pies
08-Feb-2009 11:22
You can use the "or" and "and" keywords' lower precedence for a bit of syntax candy:
<?php
$page = (int) @$_GET['page'] or $page = 1;
?>
