My PHP array of references is “magically” becoming an array of values… why?

后端 未结 3 1841
一向
一向 2021-01-11 17:06

I\'m creating a wrapper function around mysqli so that my application needn\'t be overly complicated with database-handling code. Part of that is a bit of code to parameter

3条回答
  •  再見小時候
    2021-01-11 17:35

    Pass the array as a reference:

      function setArray(&$vals) {
        foreach ($vals as $key => &$value) {
          $this->myarray[] =& $value;
        }
        $this->dumpArray();
      }
    

    My guess (which could be wrong in some details, but is hopefully correct for the most part) as to why this makes your code work as expected is that when you pass as a value, everything's cool for the call to dumpArray() inside of setArray() because the reference to the $vals array inside setArray() still exist. But when control returns to myfunc() then that temporary variable is gone as are all references to it. So PHP dutifully changes the array to string values instead of references before deallocating the memory for it. But if you pass it as a reference from myfunc() then setArray() is using references to an array that lives on when control returns to myfunc().

提交回复
热议问题