英文:
Do static and global modifiers for variables implement a non-modifiable reference?
问题
PHP文档中写道:
PHP使用引用来实现变量的静态和全局修饰符。
<?php
function test_global_ref() {
global $obj;
$new = new stdClass;
$obj = &$new;
}
function test_global_noref() {
global $obj;
$new = new stdClass;
$obj = $new;
}
test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>
由于程序的第一个输出结果是NULL,这是否意味着实现的引用是不可修改的(因此对&$new的引用在某种程度上被取消了)?文档中指出,该实现会导致意外的行为。这背后是否有合乎逻辑的解释?
英文:
The PHP doc says
> PHP implements the static and global modifier for variables in terms
> of references.
<?php
function test_global_ref() {
global $obj;
$new = new stdClass;
$obj = &$new;
}
function test_global_noref() {
global $obj;
$new = new stdClass;
$obj = $new;
}
test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>
Since the program yields NULL as the first output, is this to say that the implemented reference is non-modifiable(hence the reference to &$new is nullified somehow)? The doc says the implementation results in an unexpected behaviour. Is there a logical explanation to this?
答案1
得分: 1
这不涉及全局或静态,而是涉及引用的概念。
考虑以下代码:
$a = "a"; $b = "b";
$r = &$a;
var_dump($a, $b, $r); # a, b, a
$r = &$b;
var_dump($a, $b, $r); # a, b, b
容易理解的是,但重要的是语句 $r = &$b; 意味着将 $b 的引用复制给 $r,因此 $b 和 $r 都指向相同的值。
接下来如果你执行:
$r = $a;
var_dump($a, $b, $r); # a, a, a
语句 $r = $a; 意味着将 $a 的值复制给 $r,所以 $r 的值从 "b" 变为 "a"。由于 $b 和 $r 指向相同的值,$b 的值也变为 "a"。
最后,如果你执行:
$r = "r";
var_dump($a, $b, $r); # a, a, r
仍然只有 $b 的值被改变为 $r,$a 保持其原始值。
回到你的问题,你的第一个函数几乎等同于:
function test_global_ref(&$r) {
$b = "b";
$r = &$b;
}
$a = "a";
test_global_ref($a);
英文:
This is not about global or static, this is about the concept of reference.
Think about the following codes:
$a = "a"; $b = "b";
$r = &$a;
var_dump($a, $b, $r); # a, b, a
$r = &$b;
var_dump($a, $b, $r); # a, b, b
It's easy to understand, but the important thing is the statement $r = &$b; means copy the reference of $b to $r, so both $b and $r refer to the same value.
Next if you do:
$r = $a;
var_dump($a, $b, $r); # a, a, a
The statement $r = $a; means copy the value of $a to $r, so the value of $r changes from "b" to "a". Since both $b and $r refer to the same value, the value of $b also becomes "a".
Finally if you do:
$r = "r";
var_dump($a, $b, $r); # a, r, r
Still only the value of $b to $r is changed, $a keeps its original value.
Back to your question, your first function is almost equivalent to:
function test_global_ref(&$r) {
$b = "b";
$r = &$b;
}
$a = "a";
test_global_ref($a);
I changed the variable names and values to those corresponding to the above example, hope this is easier to understand. So the global variable $a is passed to the function as a reference $r, when you copy the reference of $b to $r, the global variable $a won't be influenced.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论