PHP Velho Oeste 2024

할당 연산자

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

할당 연산자의 값은 할당된 값입니다. 그러므로, "$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 4 notes

up
129
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
59
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
34
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
12
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)
To Top