在 PHP 中,类成员函数中的局部数组变量是否可以由类成员变量引用


In PHP, can the local array variable in class member functions referenced by class member variable?

class A {
    public $a;
    public function foo() {
        $b = array("a", "b");   
        $this->a = &$b;
    }
}

会发生什么?

$b arraypointer,当函数foo()退出时,$b消失而数组仍然存在?

如果数组也消失了,$a将失去对它的引用。

谁能为我解释一下?

我想你的意思是这样的:

是的,你可以!在这里,您将array $b指定为对$a的引用并更改$b。然后你输出$a它与更改后的$b相同!

<?php 
    class A {
        public $a;
        function foo() {
            $b = array("a", "b");
            $this->a = &$b;
            $b[] = "c";
            print_r($b);
            unset($b);
            print_r($b);
            print_r($this->a);
        }
        function foo2() {
            print_r($this->a);
        }
    }
    $test = new A();
    $test->foo();
    $test->foo2();
?>

输出:

Array ( [0] => a [1] => b [2] => c ) //$b
Notice: Undefined variable: b in C:'xampp'htdocs'Testing'index.php on line 27  //after unset $b
Array ( [0] => a [1] => b [2] => c )  //$a from the function foo
Array ( [0] => a [1] => b [2] => c )  //$a from the function foo2

评论后更新:

(带全局变量(

<?php
    global $c;
    $c = 42;
    $d = &$c;
    $c = 2;
    unset($c);    
    echo $d;

?>

输出:

2