在PHP 5.2.13中传递数组作为参考?

时间:2014-03-03 11:36:42

标签: php arrays reference

如何修复此方法以接受引用传递?

它会抛出 Fatal error: Only variables can be passed by reference

/**
 * Set a value "deep within" an associative array.
 *
 * @param array $array_ - Target array to set value on.
 * @param mixed $value - A value to set.
 * @param string $keyPath - Like 'campaign.pushMessages.sendDate'.
 */
private function setValueForKeyPath(&$array, $value, $keyPath)
{
    $keys = explode(".", $keyPath, 2); // Like [ 'campaign', 'pushMessages.sendDate' ]

    // If keys is a leaf key...
    $isLeaf = (count($keys) == 1);
    if ($isLeaf)
    {
        // ...simply set the value.
        $array[$keys[0]] = $value;
    }

    else
    {
        // ...or set a sub-array as value.
        $this->setValueForKeyPath($array[$keys[0]], $value, $keys[1]);
    }
}

0 个答案:

没有答案