PHP - 通过对象内部引用修改数组值

时间:2014-04-11 16:28:17

标签: php

如何通过引用传递数组的值来修改对象内的值?我在&处使用public function f(&$z) {运算符尝试过。

<?php
    class C {
        private $a;

        public function f($z) {
            foreach ($z as $i => $v) {
                $v = 8888;
            }
        }
    }

    $p = 4;
    $obj = new C();
    $obj->f(array('key'=>$p));
    echo $p;
?>

我想将 8888 值设置为$p变量。

小提琴:http://codepad.org/RvKU4hY1

3 个答案:

答案 0 :(得分:2)

当你1)创建数组时,你必须使用引用,2)迭代它:

<?php
  class C {
    private $a;

    public function f($z) { 
        foreach ($z as $i => &$v) {
            $v = 8888;
        }
    }
  }
    $p = 4;
    $obj = new C();
    $obj->f(array('key'=>&$p));
    echo $p;
?>

答案 1 :(得分:2)

与georg略有不同,你可以这样做;

<?php
class C {
    private $a;

    public function f($z) {
        foreach ($z as $i => $v) {
            $z[$i] = 8888;
        }
    }
}
$p = 4;
$obj = new C();
$result = array('key'=> &$p);
$obj->f($result);

echo $p;
?>

答案 2 :(得分:2)

这里的代码有说明:

<?php
    class C {
        private $a;

        public function f(&$z) { // we receive a pointer
            foreach ($z as $i => $v) {
                //  here you overwrite $v, even if it a pointer in foreach
                // It has mean when you want to do unset($v); here
                // $v = 8888;
                $z[$i] = 8888;
            }
        }
    }

    $p = 4;
    $obj = new C();
    $param = array('key'=>$p);
    $obj->f($param);
    echo $p;