downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Побитови оператори> <Аритметични оператори
[edit] Last updated: Fri, 18 Sep 2009

view this page in

Оператори за присвояване

Основният оператор за присвояване е "=". Първото ви предположение за него би могло да бъде "равно на". Не трябва. Той всъщност означава, че на левия операнд се присвоява стойността от израза на десния.

Стойността на присвоителния израз е и стойността, която бива присвоявана. Така че стойността на "$a = 3" е 3. Това ви позволява да правите някои хитри неща:

<?php

$a 
= ($b 4) + 5// $a е равно на 9, а на $b е присвоена стойност 4.

?>

Освен основния присвоителен оператор, съществуват и "комбинирани оператори" за всички оператори за двоична аритметика, обединение на масиви и низове, които ви позволяват да използвате стойности в изрази и след това да присвоявате резултата от тези изрази. Например:

<?php

$a 
3;
$a += 5// присвоява 8 на $a, както ако бяхме казали: $a = $a + 5;
$b "Ей, ти ";
$b .= "там!"// присвоява на $b "Ей, ти там!", също както $b = $b . "там!";

?>

Забележете, че присвояването копира оригиналната стойност на новата стойност (присвояване по стойност), така че промените върху едната няма да се отразят на другата. Това би могло да бъде от значение, в случаите когато трябва да копирате неща като големи масиви в тежък цикъл. Присвояването по референция също се поддържа, посредством синтаксиса $var = &$othervar;. 'Присвояването по референция' означава, че и двете променливи сочат към едни и същи данни и нищо не се копира никъде. За да научите повече за референциите, прочетете Обяснение на референциите. След PHP 5, обектите се присвояват по референция, освен ако изрично е указано друго с новата ключова дума clone.



add a note add a note User Contributed Notes Оператори за присвояване
haubertj at alfredstate dot edu 01-Sep-2011 07:19
[[   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.
Peter, Moscow 11-Feb-2011 01:44
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.
Hayley Watson 05-Feb-2008 05:54
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;
Hayley Watson 07-Oct-2007 03:22
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;
?>
adam at gmail dot com 25-Aug-2006 10:38
or you could use the xor-assignment operator..
$a ^= $b;
$b ^= $a;
$a ^= $b;
bradlis7 at bradlis7 dot com 15-Aug-2005 08:13
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 (+=, *=...).
straz at mac dot nospam dot com 20-Feb-2004 10:18
This page really ought to have table of assignment operators,
namely,

See the Arithmetic Operators page (http://www.php.net/manual/en/language.operators.arithmetic.php)
Assignment    Same as:
$a += $b     $a = $a + $b    Addition
$a -= $b     $a = $a - $b     Subtraction
$a *= $b     $a = $a * $b     Multiplication
$a /= $b     $a = $a / $b    Division
$a %= $b     $a = $a % $b    Modulus

See the String Operators page(http://www.php.net/manual/en/language.operators.string.php)
$a .= $b     $a = $a . $b       Concatenate

See the Bitwise Operators page (http://www.php.net/manual/en/language.operators.bitwise.php)
$a &= $b     $a = $a & $b     Bitwise And
$a |= $b     $a = $a | $b      Bitwise Or
$a ^= $b     $a = $a ^ $b       Bitwise Xor
$a <<= $b     $a = $a << $b     Left shift
$a >>= $b     $a = $a >> $b      Right shift

 
show source | credits | stats | sitemap | contact | advertising | mirror sites