如何通过引用传递数组的值来修改对象内的值?我在&
处使用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
变量。
答案 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;