Home  >  Article  >  Backend Development  >  php assignment operator

php assignment operator

伊谢尔伦
伊谢尔伦Original
2016-11-24 13:35:221513browse

The basic assignment operator is "=". At first you may think it is "equal to", but it is not. It actually means assigning the value of the expression on the right to the operand on the left.

The value of the assignment operation expression is the assigned value. That is, the value of "$a = 3" is 3. In this way, you can do some tricks:

<?php
$a = ($b = 4) + 5; // $a 现在成了 9,而 $b 成了 4。
?>

For arrays, the "=>" operator is used to assign values ​​to named keys. This operator has the same precedence as other assignment operators.

In addition to the basic assignment operators, there are "combining operators" suitable for all binary arithmetic, array set and string operators, which allow you to use its value in an expression and combine the result of the expression Assign it, for example:

<?php
$a = 3;
$a += 5; // sets $a to 8, as if we had said: $a = $a + 5;
$b = "Hello ";
$b .= "There!"; // sets $b to "Hello There!", just like $b = $b . "There!";
?>

Note that the assignment operation copies the value of the original variable to the new variable (assignment by value), so changing one does not affect the other. This is also suitable for copying some values ​​such as large arrays in dense loops.

There is an exception to the normal pass-by-value assignment behavior in PHP. When encountering an object, it is assigned by reference in PHP 5, unless the clone keyword is explicitly used to copy.

Reference assignment

PHP supports reference assignment, using the "$var = &$othervar;" syntax. Assignment by reference means that both variables point to the same data, nothing is copied.

Example #1 Reference assignment

<?php
$a = 3;
$b = &$a; // $b 是 $a 的引用
print "$a\n"; // 输出 3
print "$b\n"; // 输出 3
$a = 4; // 修改 $a
print "$a\n"; // 输出 4
print "$b\n"; // 也输出 4,因为 $b 是 $a 的引用,因此也被改变
?>

Since PHP 5, the new operator automatically returns a reference, so reference assignment of the result of new will issue an E_DEPRECATED error message in PHP 5.3 and later versions. In previous versions, it will Issue an E_STRICT error message.

For example the following code will generate a warning:

<?php
class C {}
/* The following line generates the following error message:
* Deprecated: Assigning the return value of new by reference is deprecated in...
*/
$o = &new C;
?>


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:php bit operatorsNext article:php bit operators