Home > Article > Backend Development > Detailed explanation of assignment operators in php
PHP Assignment operator PHP assignment operator is used to write values to variables. The basic assignment operator in PHP is "=". This means that the right-hand side assignment expression sets the value for the left-hand operand.
The value of the value 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. The precedence of this operator is the same as that of other assignment operators.
In addition to the basic assignment operators, there are "combining operators" suitable for all binary arithmetic, array collections andString operators, which can be used in an expression Use its value and assign the result of the expression to 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 one. 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 an object is encountered, it is assigned by reference in PHP 5, unless the clone keyword is explicitly used to copy. Reference assignmentPHP 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 a message in PHP 5.3 and later versions. E_DEPRECATED
Error message, in previous versions an E_STRICT error message would be issued.
For example, the following code will generate a warning:<?php class C {} $o = &new C ; ?>
The above is the detailed content of Detailed explanation of assignment operators in php. For more information, please follow other related articles on the PHP Chinese website!