( - 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 の答えは 16 になり、18 とはなりません。 これは乗算演算子("*")は、加算演算子("+")より高い優先順位を有するか らです。必要に応じて強制的に優先順位を設定するために括弧を使用する ことが可能です。例えば、18と評価するためには、 (1 + 5) * 3 とします。
演算子の優先順位が等しい場合は、その結合性によって評価順 (右から評価するのか、あるいは左から評価するのか) が決まります。 以下の例を参照ください。
次の表では、優先順位が高い順に演算子を挙げています。 同じ行にある演算子は優先順位が等しくなります。そのような場合は、 結合時の評価にしたがって評価順が決まります。
| 結合時の評価 | 演算子 | 追加情報 |
|---|---|---|
| 結合しない | clone new | clone および new |
| left | [ | array() |
| 結合しない | ++ -- | 加算子/減算子 |
| right | ~ - (int) (float) (string) (array) (object) (bool) @ | 型 |
| 結合しない | instanceof | 型 |
| right | ! | 論理演算子 |
| left | * / % | 代数演算子 |
| left | + - . | 代数演算子 そして 文字列演算子 |
| left | << >> | ビット演算子 |
| 結合しない | < <= > >= <> | 比較演算子 |
| 結合しない | == != === !== | 比較演算子 |
| left | & | ビット演算子 そして リファレンス |
| left | ^ | ビット演算子 |
| left | | | ビット演算子 |
| left | && | 論理演算子 |
| left | || | 論理演算子 |
| left | ? : | 三項演算子 |
| right | = += -= *= /= .= %= &= |= ^= <<= >>= => | 代入演算子 |
| left | and | 論理演算子 |
| left | xor | 論理演算子 |
| left | or | 論理演算子 |
| left | , | さまざまな利用法 |
演算子の優先順位が同じ場合、 結合時の評価が left の場合は式が左から右に評価され、一方 right の場合は その逆となります。
例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
// ++ と + を同時に使ったときの挙動は未定義です
$a = 1;
echo ++$a + $a++; // 4 になるかもしれないし、5 になるかもしれません
?>
注意:
= は他のほとんどの演算子よりも優先順位が低いはずなのにもかかわらず、 PHP は依然として if (!$a = foo()) のような式も許します。この場合は foo() の返り値が $a に代入されます。
Christopher Schramm
02-Jul-2011 06:29
charles at pilger dot com dot br
09-Feb-2011 09: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
13-Jul-2010 01: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 01: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 08: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;
?>
