Home  >  Article  >  Backend Development  >  Do you know the difference between assignment by value and assignment by reference in PHP?

Do you know the difference between assignment by value and assignment by reference in PHP?

怪我咯
怪我咯Original
2017-07-16 10:00:151683browse

Assignment by value: When the value of an expression is assigned to a variable, the value of the entire original expression is assigned to the target variable. This means that, for example, changing the value of one variable while the value of one variable is assigned to another variable will not affect the other variable.

The code is as follows:

<?php <?php 
$a=123; $a=123; 
$b=$a; $b=&$a; 
$a=321; $a=321; 
Echo”$a,$b”;//显示”321,123” Echo”$a,$b”;//显示”321,321” 
?>

Reference assignment: The new variable simply references the original variable. Changing the new variable will affect the original variable using reference assignment. , simply add an & symbol in front of the variable to be assigned (source variable)
Type Trick PHP does not require (or does not support) explicit type definitions in variable definitions; the variable type is determined based on the context in which the variable is used. decided. In other words, if you assign a string value to the variable var, var becomes a string. If you assign an integer value to var, it becomes an integer.
TypeCoercion
The allowed coercions are: (int), (integer) - converted to integer (bool), (boolean) - converted to Boolean Type (float), (double), (real) - Convert to floating point type (string) - Convert to string (array) - Convert to array (object) - Convert to object Settype() Type conversion
Function Settype()

<?php 
$foo = "5bar"; // string 
$bar = true; // boolean 

settype($foo, "integer"); // $foo 现在是 5 (integer) 
settype($bar, "string"); // $bar 现在是 "1" (string) 
?>

The above is the detailed content of Do you know the difference between assignment by value and assignment by reference in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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