代入演算子

代入演算子の基本となるものは "=" です。この演算子に関して最初に 思い付く意味は"等しい"であるかもしれません。しかし、そうではありません。 本当は、左オペランドに右オペランドの式の値を設定する("得て代入する") ことを意味します。

代入式の値は、代入される値です。つまり、"$a = 3" の値は、3 です。 これにより、以下のようなトリッキーなことができるようになります。

<?php

$a 
= ($b 4) + 5// $a は 9 に等しくなり、$b には 4 が代入されます

?>

基本代入演算子に加えて、全ての 演算子、配列結合および文字列演算子に関して 「複合演算子」があります。 これにより、式の中の値を使用し、その値をその式の結果とすることができます。 例えば、

<?php

$a 
3;
$a += 5// $a を 8 にセットします。$a = $a + 5; と同じです。
$b "Hello ";
$b .= "There!"// $bを"Hello There!"にセットします。$b = $b . "There!";と同じです。

?>

代入は、元の変数を新しい変数にコピーする(値による代入)ため、 片方の変数に対する変更はもう片方に影響を与えないということに 注意してください。この動作により、密なループの内側で大きな配列のようなものを コピーする必要がある場合には問題を生じる可能性があります。

PHP では通常は値による代入になりますが、 オブジェクトは参照で代入されます。 オブジェクトを明示的にコピーするには clone キーワードを使います。

参照による代入

参照による代入もサポートしており、 "$var = &$othervar;" 構文で使うことができます。 参照による代入とは、両方の変数が同じデータを指すようにするということです。 データのコピーは発生しません。

例1 参照による代入

<?php
$a 
3;
$b = &$a// $b は $a への参照です

print "$a\n"// 表示: 3
print "$b\n"// 表示: 3

$a 4// change $a

print "$a\n"// 表示: 4
print "$b\n"// 表示: 4
              // $b の参照先は $a であり、その値が変わったからです
?>

new 演算子は自動的に参照を返します。そのため、 new の結果を参照で代入するとエラーが発生します。

<?php
class {}

$o = &new C;
?>

上の例の出力は以下となります。

Parse error: syntax error, unexpected 'new' (T_NEW) in …

参照に関する詳細な情報やその使い方については、このマニュアルの リファレンスに関する説明 をご覧ください。

算術代入演算子

同一の結果になる操作 演算
$a += $b $a = $a + $b 加算
$a -= $b $a = $a - $b 減算
$a *= $b $a = $a * $b 乗算
$a /= $b $a = $a / $b 除算
$a %= $b $a = $a % $b 剰余
$a **= $b $a = $a ** $b べき乗

ビット代入演算子

同一の結果になる操作 演算
$a &= $b $a = $a & $b ビット積
$a |= $b $a = $a | $b ビット和
$a ^= $b $a = $a ^ $b 排他的論理和
$a <<= $b $a = $a << $b 左シフト
$a >>= $b $a = $a >> $b 右シフト

その他の代入演算子

同一の結果になる操作 演算
$a .= $b $a = $a . $b 文字列の結合
$a ??= $b $a = $a ?? $b Null合体
add a note add a note

User Contributed Notes 8 notes

up
93
Peter, Moscow
13 years ago
Using $text .= "additional text"; instead of $text =  $text ."additional text"; can seriously enhance performance due to memory allocation efficiency.

I reduced execution time from 5 sec to .5 sec (10 times) by simply switching to the first pattern for a loop with 900 iterations over a string $text that reaches 800K by the end.
up
56
Robert Schneider
9 years ago
Be aware of assignments with conditionals. The assignment operator is stronger as 'and', 'or' and 'xor'.

<?php
$x
= true and false;   //$x will be true
$y = (true and false); //$y will be false
?>
up
30
Hayley Watson
16 years ago
bradlis7 at bradlis7 dot com's description is a bit confusing. Here it is rephrased.

<?php
$a
= 'a';
$b = 'b';

$a .= $b .= "foo";

echo
$a,"\n",$b;?>
outputs

abfoo
bfoo

Because the assignment operators are right-associative and evaluate to the result of the assignment
<?php
$a
.= $b .= "foo";
?>
is equivalent to
<?php
$a
.= ($b .= "foo");
?>
and therefore
<?php
$b
.= "foo";
$a .= $b;
?>
up
6
asc at putc dot de
8 years ago
PHP uses a temporary variable for combined assign-operators (unlike JavaScript), therefore the left-hand-side (target) gets evaluated last.

Input:
$a += $b + $c;

Meaning:
$a = ($b + $c) + $a;

Not:
$a = $a + ($b + $c);

This can be important if the target gets modified inside the expression.

$a = 0;
$a += (++$a) + (++$a); // yields 5 (instead of 4)
up
-15
ma dot bx dot ar at gamil dot com
9 years ago
Document says:
"An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword."

But it's not very accurate! Considering this code:
<?php
$a
= new StdClass;
$b = $a;

$a = new StdClass;

var_dump ($a, $b);
?>

Output:
object(stdClass)#2 (0) {
}
object(stdClass)#1 (0) {
}
Note: #2 and #1 means two different objects.

But this code:
<?php
$a
= new StdClass;
$b = &$a;

$a = new StdClass;

var_dump ($a, $b);
?>

Output will be:

object(stdClass)#2 (0) {
}
object(stdClass)#2 (0) {
}

Note: Still pointing to the same object.

And this shows that that exception is not valid, PHP assignment for objects still makes a copy of variable and does not creates a real reference, albeit changing an object variable members will cause both copies to change.
So, I would say assignment operator makes a copy of 'Object reference' not a real object reference.
up
-14
Hayley Watson
16 years ago
You could also take adam at gmail dot com's xor-assignment operator and use the fact that it's right-associative:

$a ^= $b ^= $a ^= $b;
up
-31
bradlis7 at bradlis7 dot com
18 years ago
Note whenever you do this

<?php
$a
.= $b .= "bla bla";
?>

it comes out to be the same as the following:

<?php
$a
.= $b."bla bla";
$b .= "bla bla";
?>

So $a actually becomes $a and the final $b string. I'm sure it's the same with numerical assignments (+=, *=...).
up
-46
haubertj at alfredstate dot edu
12 years ago
[[   Editor's note: You are much better off using the foreach (array_expression as $key => $value) control structure in this case   ]]

When using

<php
while ($var = current($array) {
#do stuff
next($aray)
?>

to process an array, if current($array) happens to be falsy but not === false it will still end the loop.  In such a case strict typing must be used.

Like this:

<php
while (($var = current($array)) !== FALSE) {
#do stuff
next($aray)
?>

Of course if your array may contain actual FALSE values you will have to deal with those some other way.
To Top