Home > Backend Development > PHP Tutorial > php 引用只允许定义在函数参数中,实时传递引用是禁止的

php 引用只允许定义在函数参数中,实时传递引用是禁止的

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:09:40
Original
1026 people have browsed it

<code>14. 引用只允许定义在函数参数中,实时传递引用是禁止的。例如:
// 引用定义在函数参数-允许的
function defineRefInMethod(&$a)
{
    $a = 'a';
} 
defineRefInMethod($b);

echo $b; // 'a'

// 实时传递引用-禁止的
function callTimePassRef($a)
{
    $a = 'a';
}

callTimePassRef(&$c);

echo $c; // 'a'
</code>
Copy after login
Copy after login

上面两张情况分别适用那些场景?

回复内容:

<code>14. 引用只允许定义在函数参数中,实时传递引用是禁止的。例如:
// 引用定义在函数参数-允许的
function defineRefInMethod(&$a)
{
    $a = 'a';
} 
defineRefInMethod($b);

echo $b; // 'a'

// 实时传递引用-禁止的
function callTimePassRef($a)
{
    $a = 'a';
}

callTimePassRef(&$c);

echo $c; // 'a'
</code>
Copy after login
Copy after login

上面两张情况分别适用那些场景?

有时候,我们会这样处理数组

$arr = [...];
foreach($arr as &$value){
    // do something here...
}

print_r($arr);
Copy after login

1、前者是传址,后者是传值。前者在函数体内对&修饰的变量产生更改会产生全局更改,而后者不会。函数只能有一个return值,一般对单个变量进行更改时使用返回值,对多个变量进行更改时只能使用&。
2、引用只允许定义在函数参数中。这一句表示怀疑,不知道出处是何处,而且后半句的解释令人匪夷所思。

实际上第二种用法是会报错的。

假设不报错的话,也是很奇葩的一种写法,因为地址是只读不可写的。

Related labels:
php
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template