Home Backend Development PHP Tutorial Detailed explanation of php reference (&) symbol

Detailed explanation of php reference (&) symbol

Jul 25, 2016 am 08:57 AM

  1. $a="ABC";
  2. $b =&$a;
  3. echo $a;//Output here: ABC
  4. echo $b;//Output here: ABC
  5. $b= "EFG";
  6. echo $a;//The value of $a here becomes EFG, so EFG is output
  7. echo $b;//EFG is output here
  8. ?>
Copy code

2, function transfer address transfer I won’t go into details about call by address. The code is given directly below.

  1. function test(&$a)
  2. {
  3. $a=$a+100;
  4. }
  5. $b=1;
  6. echo $b;//output 1
  7. test($ b); //What $b is passed to the function here is actually the memory address where the variable content of $b is located. By changing the value of $a in the function, the value of $b can be changed
  8. echo "
    " ;
  9. echo $b;//Output 101
  10. ?>
Copy code

Note: If you test(1); here, an error will occur.

3, function reference returns

  1. function &test()

  2. {
  3. static $b=0;//Declare a static variable
  4. $b=$b+1;
  5. echo $b;
  6. return $b;
  7. }

  8. $a=test();//This statement will output the value of $b as 1

  9. $a=5;
  10. $a=test(); //This statement will output the value of $b as 2

  11. $a=&test();//This statement will output the value of $b as 3

  12. $a=5;
  13. $ a=test();//This statement will output the value of $b as 6
  14. ?>
Copy code

Explanation: In this way, $a=test(); actually does not get a function reference return, which is no different from an ordinary function call. As for the reason: PHP regulations PHP stipulates that what is obtained through $a=&test(); is the reference return of the function. As for what is a reference return (the PHP manual says: Reference return is used when you want to use a function to find which variable the reference should be bound to.).

$a=test() method of calling a function only assigns the value of the function to $a, and any changes to $a will not affect $b in the function. When calling a function through $a=&test(), its function is to point the memory address of the $b variable in return $b and the memory address of the $a variable to the same place. That is to say, the effect equivalent to this is produced ($a=&b;), so changing the value of $a also changes the value of $b, so after executing

  1. class a{
  2. var $abc="ABC";
  3. }
  4. $b=new a;
  5. $c=$b;
  6. echo $b->abc;//here Output ABC
  7. echo $c->abc;//Output ABC here
  8. $b->abc="DEF";
  9. echo $c->abc;//Output DEF here
  10. ?>
Copy the code

The above code is the effect of running in PHP5 In PHP5, object copying is achieved through references. In the above column, $b=new a; $c=$b; is actually equivalent to $b=new a; $c=&$b; The default in PHP5 is to call objects by reference, but sometimes you may want to create a copy of the object and hope that changes to the original object will not affect the copy. For this purpose, PHP defines a special method called __clone .

5, the role of quotes If the program is relatively large, there are many variables referencing the same object, and you want to manually clear the object after using it, I personally recommend using the "&" method, and then using $var=null to clear it. Otherwise, use the default of php5 Method. In addition, for transferring large arrays in php5, it is recommended to use the "&" method, after all, it saves memory space.

6, unquote When you unset a reference, you just break the binding between the variable name and the variable's contents. This does not mean that the variable contents are destroyed. For example:

  1. $a = 1;
  2. $b =& $a;
  3. unset ($a);
  4. ?>
Copy code

will not unset $b, Just $a.

7, global reference When you declare a variable with global $var you actually create a reference to the global variable. It's the same as this:

  1. $var =& $GLOBALS["var"];
  2. ?>
Copy code

This means that, for example, unset $var will not unset a global variable.

$this In an object method, $this is always a reference to the object that calls it.

The pointing (similar to pointer) function of the address in php is not implemented by the user himself, but is implemented by the Zend core. The reference in php adopts the principle of "copy-on-write", that is, unless a write operation occurs, it points to the same Address variables or objects will not be copied.

1, if you have the following code

$a="ABC"; $b=$a;

In fact, at this time, $a and $b both point to the same memory address, rather than $a and $b occupying different memories

2. If you add the following code to the above code

$a="EFG";

Since the data in the memory pointed to by $a and $b needs to be rewritten, the Zend core will automatically determine at this time to automatically produce a data copy of $a for $b and re-apply for a piece of memory for storage.

This is about the usage of the reference symbol & in php. I hope it can help everyone. Articles you may be interested in: Detailed explanation of examples of php reference passing by value Example code quoted by php Detailed explanation of examples quoted by php Explanation about PHP references Example analysis of PHP variable references, function addresses and object references Detailed introduction to php reference passing by value Understand the difference between passing by value and passing by reference in PHP through examples Look at the efficiency issues of php address reference through examples About the problem of changing the variable value of the php reference address Quotes in PHP, "&" explanation



Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

What are Enumerations (Enums) in PHP 8.1? What are Enumerations (Enums) in PHP 8.1? Apr 03, 2025 am 12:05 AM

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What is REST API design principles? What is REST API design principles? Apr 04, 2025 am 12:01 AM

RESTAPI design principles include resource definition, URI design, HTTP method usage, status code usage, version control, and HATEOAS. 1. Resources should be represented by nouns and maintained at a hierarchy. 2. HTTP methods should conform to their semantics, such as GET is used to obtain resources. 3. The status code should be used correctly, such as 404 means that the resource does not exist. 4. Version control can be implemented through URI or header. 5. HATEOAS boots client operations through links in response.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

What are anonymous classes in PHP and when might you use them? What are anonymous classes in PHP and when might you use them? Apr 04, 2025 am 12:02 AM

The main function of anonymous classes in PHP is to create one-time objects. 1. Anonymous classes allow classes without names to be directly defined in the code, which is suitable for temporary requirements. 2. They can inherit classes or implement interfaces to increase flexibility. 3. Pay attention to performance and code readability when using it, and avoid repeatedly defining the same anonymous classes.

See all articles