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

时间:2014-10-27 14:53:06

标签: php variables pointers reference local

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

将会发生什么?

$bpointerarray,当函数foo()退出时,$b消失,数组仍在那里?

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

任何人都能为我解释一下吗?

1 个答案:

答案 0 :(得分:0)

我认为你的意思是这样的:

是的,你可以!您可以在此处指定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