phppass-by-referencereturn-by-referencezikulapass-by-reference-value

How to re-code PHP assign-by-reference usage


My deprecation checker is throwing this error:

Using deprecated language feature assign by reference(&=) Since PHP 5.3 use normal assignment instead.

So, I am trying to figure out how to re-code the methods in this class to not use by reference or at least use it properly (if it is allowed at all - which I'm not clear on either).

below is the portion of the class using by reference. The entire class is here, the test and the deprecation checker log is here.

I would like some help recoding the class to remove the use of by reference

class ParameterBag
{
    /**
     * Sets value.
     *   can use 'key' = ['subkey' => value, 'subkey2' => value2]
     *      or
     *   'key.subkey' = value
     *   'key.subkey2' = value2
     *
     * @param $key
     * @param $value
     */
    public function set($key, $value)
    {
        $parameters = &$this->resolvePath($key, true);
        $key = $this->resolveKey($key);
        $parameters[$key] = $value;
    }

    /**
     * Resolves a path in parameters property and returns it as a reference.
     *
     * This method allows structured namespacing of parameters.
     *
     * @param string  $key         Key name
     * @param boolean $writeContext Write context, default false
     *
     * @return array
     */
    private function &resolvePath($key, $writeContext = false)
    {
        $array = &$this->parameters;
        $key = (strpos($key, $this->ns) === 0) ? substr($key, 1) : $key;

        // Check if there is anything to do, else return
        if (!$key) {
            return $array;
        }

        $parts = explode($this->ns, $key);
        if (count($parts) < 2) {
            if (!$writeContext) {
                return $array;
            }

            $array[$parts[0]] = [];

            return $array;
        }

        unset($parts[count($parts) - 1]);

        foreach ($parts as $part) {
            if (!array_key_exists($part, $array)) {
                if (!$writeContext) {
                    return $array;
                }

                $array[$part] = [];
            }

            $array = &$array[$part];
        }

        return $array;
    }
}

Solution

  • This appears to be a bug in the deprecation tool. According to Deprecated features in PHP 5.3.x:

    • Assigning the return value of new by reference is now deprecated.
    • Call-time pass-by-reference is now deprecated.

    But assignment by reference in general is not deprecated, and Returning References says:

    To use the returned reference, you must use reference assigment