Table of Contents
What can be passed by reference:
Home Backend Development PHP Tutorial What are PHP quotes? Introduction to quoting in php (code example)

What are PHP quotes? Introduction to quoting in php (code example)

Sep 17, 2018 pm 03:44 PM
php

The content of this article is about what is PHP reference? The introduction (code examples) quoted in php has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. What is a reference

In PHP, a reference refers to accessing the same variable content with different names.
The variable names and variable contents in PHP are different, so the same content can have different names.
The closest analogy is the Unix file name and the file itself - the variable name is the directory entry, and the variable content is the file itself. References can be thought of as hard links in a Unix file system.

References in PHP are not like pointers in C: for example you cannot do pointer arithmetic on them. The reference is not an actual memory address, but a symbol table alias.

2. Reference features

PHP’s reference allows two variables to point to the same content.

$a =& $b;
Copy after login

This means $a and $b point to the same variable.

$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.

If an array with a reference is copied, its value will not be dereferenced. The same goes for passing array values ​​to functions.

$a = 'a';

$arr1 = [
    'a' => $a,
    'b' => &$a, // $arr1['b'] 与 $a 指向同一个变量
];

// 将 $arr1 传值赋值给 $arr2
$arr2 = $arr1;

print_r($arr2); // $arr2 的值为 ['a' => 'a', 'b' => 'a']

// 修改 $a 的值为 'b'
$a = 'b';

print_r($arr2); // $arr2 的值为 ['a' => 'a', 'b' => 'b']


function foo($arr){
    // 将 $arr['b'] 的值改为 'c';
    $arr['b'] = 'c';
}

echo $a; // $a 的值为 'b'

// 将 $arr1 传入函数
foo($arr1);

echo $a; // $a 的值为 'c'
Copy after login

If an undefined variable is assigned by reference, passed by reference parameter, or returned by reference, the variable will be automatically created.

// 定义函数 foo(),通过引用传递参数
function foo(&$var) { }

foo($a); // 创建变量 $a,值为 NULL
var_dump($a); // NULL

foo($b['b']); // 创建数组 $b = ['b' => NULL]
var_dump(array_key_exists('b', $b)); // bool(true)

$c = new StdClass;
foo($c->d); // 创建对象属性 $c->d = NULL
var_dump(property_exists($c, 'd')); // bool(true)
Copy after login

If a reference is assigned to a variable declared as global inside a function, the reference is only visible inside the function. This can be avoided by using the $GLOBALS array.

$var1 = 'var1';
$var2 = 'var2';

function global_references($use_globals)
{
    global $var1, $var2;
    if (!$use_globals) {
        $var2 = & $var1; // $var2 只在函数内部可见
    } else {
        $GLOBALS["var2"] = & $var1; // $GLOBALS["var2"]在全球范围内也可见
    }
}

global_references(false);
echo "var2 is set to '$var2'\n"; // var2 is set to 'var2'
global_references(true);
echo "var2 is set to '$var2'\n"; // var2 is set to 'var1'
Copy after login

You can think of global $var; as the abbreviation of $var =& $GLOBALS['var'];. Thus assigning another reference to $var only changes the reference to the local variable.

Assign a value to a variable with a reference in the foreach statement, and the referenced object is also changed.

$ref = 0;
$row = & $ref;
foreach ([1, 2, 3] as $row) {
    // do something
}
echo $ref; // 3 - 遍历数组的最后一个元素
Copy after login

3. Pass by reference

You can pass a variable to a function by reference, so that the function can modify the value of its parameter.

function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);

echo $a; // 6
Copy after login
Copy after login

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.

What can be passed by reference:

  • Variables

  • References returned from functions

Passing variables by reference

function foo(&$var)
{
    $var++;
}

$a=5;
foo($a);

echo $a; // 6
Copy after login
Copy after login

Passing by reference From a function Returned reference

function foo(&$var)
{
    $var++;
    echo $var; // 6
}

function &bar()
{
    $a = 5;
    return $a;
}

foo(bar());
Copy after login

You cannot pass functions, expressions, values, etc. by reference

function foo(&$var)
{
    $var++;
}

function bar() // 注意,这个函数不返回引用
{
    $a = 5;
    return $a;
}

foo(bar()); // 自 PHP 5.0.5 起导致致命错误,自 PHP 5.1.1 起导致严格模式错误,自 PHP 7.0 起导致 notice 信息

foo($a = 5); // 表达式,不是变量。PHP Notice:  Only variables should be passed by reference

foo(5); // PHP Fatal error:  Only variables can be passed by reference
Copy after login

4. Return by reference

Return by reference can be used when you want to use a function to find the variable to which a reference should be bound.
Don't use return references to increase performance, the engine is smart enough to optimize itself. Only return references if there is a valid technical reason!

class Foo {
    public $value = 42;

    public function &getValue() {
        return $this->value;
    }
}

$foo = new Foo;
// $myValue 是 $obj->value 的引用.
$myValue = &$foo->getValue();
// 将 $foo->value 修改为 2
$foo->value = 2;
echo $myValue;  // 2
Copy after login
is different from parameter reference passing. Reference return must use the ampersand in two places - indicating that a reference is returned, not a usual copy. It also points out that $myValue is bound as a reference, and Not an ordinary assignment.

Reference return can only return variables. If you try to return a reference from a function like this: return intval($this->value);, you will get an error because the function is trying to return the result of an expression rather than a referenced variable. You can only return reference variables from functions - there is no other way.

class Foo {
    public $value = 42;

    public function &getValue() {
        return intval($this->value); // PHP Notice:  Only variable references should be returned by reference
    }
}

$foo = new Foo;
// $myValue 是 $obj->value 的引用.
$myValue = &$foo->getValue();
Copy after login

5. Unreference

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.

$a = 1;
$b = & $a;
unset($a);

echo $b; // 1
Copy after login

6. Found that

Many PHP syntax structures are implemented through the reference mechanism, so everything above about reference binding also applies to these structures.

global reference

When you declare a variable with global $var, you actually create a reference to the global variable inside the function. In other words, the effect of doing this is the same:

global $var;

$var =& $GLOBALS["var"];
Copy after login

This means that unset $var will not unset the global variable $GLOBALS["var"].

$this

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

The above is the detailed content of What are PHP quotes? Introduction to quoting in php (code example). For more information, please follow other related articles on the PHP Chinese website!

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles