할당 연산자

기본 할당 연산자는 "="입니다. 처음에는 이것을 "같다"로 생각할 수 있습니다. 아닙니다. 실제로는 왼쪽 연산수가 오른쪽 표현의 값으로 설정됨을 의미합니다. ("를 설정"입니다)

할당 연산자의 값은 할당된 값입니다. 그러므로, "$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 = $b . "There!";와 마찬가지로, $b를 "Hello There!"로 설정

?>

할당은 원래 값을 새로운 것으로 복사하기 때문에(값으로 할당), 하나의 변경은 다른 것에 영향을 주지 않습니다. 또한 빠듯한 루프 안에서 커다란 배열을 복사해야할 필요성이 존재하게 됩니다. $var = &$othervar; 구문을 사용해서, 참조로 할당도 지원합니다. '참조로 할당'은 두 변수가 같은 데이터를 가리키는 것을 의미하며, 아무것도 복사하지 않습니다. 참조에 대해서 알아보려면, 참조 설명을 읽어보십시오. PHP 5부터, 객체는 명시적으로 새로운 것을 만드는 clone 키워드를 사용하지 않는 한 참조로 할당됩니다.

add a note add a note

User Contributed Notes 8 notes

up
94
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
55
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
29
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
-14
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
-15
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
-51
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