Examples of Features and Uses of Reference Types and Value Types in PHP
- 2021-11-29 06:12:22
- OfStack
This article illustrates the functions and usage of reference types and value types in PHP. Share it for your reference, as follows:
The four simple types in PHP and the complex type array are all value types. Inter-type assignment passes a value, that is, creates a copy to a new variable.
For example:
$int1 = 123;
$int2 = $int1;// What you pass directly is the value, just doing 1 A man named int1 The copy of is called int2
$int2 = 456;
echo $int1;// Output 123
echo $int1 === $int2;// Be false
$int1 = 123;
$int2 = &$int1;// Take the address character and pass a reference
$int2 = 456;
echo $int1;// Output 456
echo $int1 === $int2;// Output 1. Is true
Objects are of reference type, and the default is to pass a reference, that is, the new variable is an alias of the old variable.
class Person{
public $name;
}
$p1 = new Person();
$p1->name = 'Sheldon';
$p2 = $p1;
$p2->name = 'Leonard';
echo $p1->name;// Output: Lenoard
echo $p1 === $p2;// Output: 1 I.e. congruence
If you want to get a copy of the object (which copies all the properties of the old variable) so that they do not affect each other, you can use the clone keyword.
class Person {
public $name;
}
$p1 = new Person();
$p1->name = 123;
$p2 = clone $p1;
echo $p2->name;// Output 123
$p2->name = 456;
echo $p1->name;// Output 123
More readers interested in PHP can check out the topics of this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"
I hope this article is helpful to everyone's PHP programming.