【问题标题】:php variable as a value instead of a referencephp 变量作为值而不是引用
【发布时间】:2023-03-10 17:04:02
【问题描述】:

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

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

这是我的笔记的功能

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()
    );

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

【问题讨论】:

    标签: php arrays variables


    【解决方案1】:

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

    $f = &$this->form;
    

    并删除它

    $this->form = $f;
    

    详细信息docs

    【讨论】:

    • 在我的武器库中可能不常见但很好。谢谢
    • 总是很高兴知道什么是可能的,我们永远不知道什么时候会需要东西 :) 祝你好运!
    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    相关资源
    最近更新 更多