search
HomeBackend DevelopmentPHP TutorialReferences in PHP, '&' explained

  1. $a =& $b
  2. ?>
Copy code

This means $a and $b point to the same variable. Note: $a and $b are exactly the same here. It’s not that $a points to $b or vice versa, but that $a and $b point to the same place. The same syntax can be used in functions, which return references, and in the new operator (PHP 4.0.4 and later):

  1. $bar =& new fooclass();
  2. $foo =& find_var ($bar);
  3. ?>
Copy code

Note: No & operator is used Causes a copy of the object to be generated. If you use $this in a class, it will apply to the current instance of that class. Assignment without & will copy the instance (e.g. object) and $this will be applied to the copy, which is not always the desired result. Due to performance and memory consumption issues, usually you only want to work on one instance.

Although you can use the @ operator to turn off any error messages in the constructor, such as @new, this has no effect when using the &new statement. This is a limitation of the Zend engine and will cause a parsing error.

The second thing that references do is pass variables by reference. This is accomplished by creating a local variable within the function and that variable references the same content in the calling scope. For example:

  1. function foo (&$var)

  2. {
  3. $var++;
  4. }
  5. $a=5;

  6. foo ($ a);
  7. ?>
Copying the code

will make $a become 6. This is because in function foo the variable $var points to the same thing that $a points to. See Passing by Reference for a more detailed explanation. The third thing that references do is reference returns.

What a quote is not As mentioned before, references are not pointers. This means that the following construct will not produce the effect you expect:

  1. function foo (&$var)
  2. {
  3. $var =& $GLOBALS[ "baz "];
  4. }
  5. foo($bar);
  6. ?>
Copy the code

This will cause the $var variable in the foo function to be bound to $bar when the function is called, but then re-bound to $GLOBALS[ "baz "]. It is not possible to bind $bar to another variable within the function call scope through the reference mechanism, because there is no variable $bar in function foo (it is represented as $var, but $var only has the variable content and no call symbol table name-to-value binding).

Pass by reference You can pass a variable by reference to a function so that the function can modify the value of its argument. The syntax is as follows:

  1. function foo (&$var)

  2. {
  3. $var++;
  4. }
  5. $a=5;

  6. foo ($ a);
  7. // $a is 6 here
  8. ?>
Copy code

Note that there are no reference symbols in the function call - only in the function definition. The function definition alone is enough for parameters to be passed correctly by reference.

The following can be passed by reference: Variables, such as foo($a)

New statement, such as foo(new foobar())

Reference returned from function, for example:

  1. function &bar()
  2. {
  3. $a = 5;
  4. return $a;
  5. }
  6. foo(bar());
  7. ?>
Copy code

See reference return for detailed explanation.

Any other expression cannot be passed by reference and the result is undefined. For example, the following example of passing by reference is invalid:

  1. function bar() // Note the missing &

  2. {
  3. $a = 5;
  4. return $a;
  5. }
  6. foo(bar());< ;/p>
  7. foo($a = 5) // Expression, not a variable

  8. foo(5) // Constant, not a variable
  9. ?>
Copy code

These conditions are available in PHP 4.0.4 and later versions.

Quote return Reference return is used when you want to use a function to find which variable the reference should be bound to. When returning a reference, use this syntax:

  1. function &find_var ($param)

  2. {
  3. return $found_var;
  4. }
  5. $foo =& find_var ($bar) ;

  6. $foo-> x = 2;
  7. ?>
Copy code

In this example, the properties of the object returned by the find_var function will be set (Translator: referring to the $foo-> x = 2; statement) instead of copied, just like without using reference syntax .

Note: Different from parameter passing, the ampersand must be used in both places here - to indicate that a reference is returned, not a usual copy, and also to indicate that $foo is bound as a reference, not a normal copy. Assignment.

Unquote When you unset a reference, you just break the binding between the variable name and the variable content. 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.

An analogy between this and Unix’s unlink call may help to understand.

Quote positioning Many PHP syntax structures are implemented through the reference mechanism, so everything mentioned above about reference binding also applies to these structures. Some constructs, such as pass-by-reference and return, have already been mentioned above. Other structures using references are:

global quote When declaring a variable with global $var you actually create a reference to the global variable. That is the same as doing:

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

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

$this In an object method, $this is always a reference to the object that calls it. Articles you may be interested in: 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



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
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Describe different HTTP caching headers (e.g., Cache-Control, ETag, Last-Modified).Apr 17, 2025 am 12:22 AM

Key players in HTTP cache headers include Cache-Control, ETag, and Last-Modified. 1.Cache-Control is used to control caching policies. Example: Cache-Control:max-age=3600,public. 2. ETag verifies resource changes through unique identifiers, example: ETag: "686897696a7c876b7e". 3.Last-Modified indicates the resource's last modification time, example: Last-Modified:Wed,21Oct201507:28:00GMT.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1?Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP: An Introduction to the Server-Side Scripting LanguagePHP: An Introduction to the Server-Side Scripting LanguageApr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP and the Web: Exploring its Long-Term ImpactPHP and the Web: Exploring its Long-Term ImpactApr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

Why Use PHP? Advantages and Benefits ExplainedWhy Use PHP? Advantages and Benefits ExplainedApr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)