php变量作为值而不是引用

时间:2015-11-22 17:58:40

标签: php arrays variables

我不确定如何提出这个问题,这就是为什么我认为我无法找到合适的答案......

我有一个简单的函数,在函数内部我将现有数组赋给变量。通过更改变量,我也想更新数组。我很清楚我可以通过将可变数据推回到阵列来实现这一点,但我很好奇我是否能以更简单的方式使用它...几乎就像我一样将变量存储为值而不是对数组的引用。

这里有我的笔记功能

function __construct($name, $action, $a){ # $a accepts a series of multidimensional sub-arrays
        $f = $this -> form; #passing the reference in here
        $f['name'] = $name; #ref 
        $f['action'] = $action; #ref 
        foreach($a as $k => $v){
            if(is_array($f[$k])){
                array_push($f[$k], $v);
            }else{
                $f[$k] = $v;
            }
        }
        # $f now contains a new value however I want to know if it's possible to make $f directly change $this -> form without a back reference
        $this -> form = $f; #this solves the problem but is there a better way?
        var_dump($this -> form);
    }

它不应该有很大的不同,但这里是$ this - >形式

protected $form = array(
        "title" => "",
        "name" => "",
        "id" => "",
        "class" => "Frm-cb", #default class for all forms
        "action" => "",
        "method" => "POST",
        "rel" => "",
        "topmsg" => "",
        "autocomplete" => "",
        "inputs" => array(),
        "buttons" => array(),
        "props" => array(),
        "attributes" => array()
    );

只是好奇它是否可能 - 谢谢!

1 个答案:

答案 0 :(得分:2)

是的,但这并不常见。你可以这样做:

$f = &$this->form;

并删除此

$this->form = $f;

docs的详细信息。