Plugin-php: Ampersands (&) being removed from reference binding assignments

Created on 4 Nov 2019  路  5Comments  路  Source: prettier/plugin-php

@prettier/plugin-php v0.11.2
Playground link

Input:

<?php

class Router {

    // ...

    static function &trie_insert(&$trie, $path_segments, $index) {
        if (!isset($path_segments[$index])) {
            return $trie;
        }
        $segment = $path_segments[$index];

        if (strlen($segment) > 0 && $segment[0] === '*') {
            $node = &self::trie_insert_wildcard_node($trie, $segment);
        } elseif (strlen($segment) > 0 && $segment[0] === ':') {
            $node = &self::trie_insert_param_node($trie, $segment);
        } else {
            $node = &self::trie_insert_static_node($trie, $segment);
        }
        return self::trie_insert($node, $path_segments, $index + 1);
    }
}

Output:

<?php

class Router
{
    // ...

    static function &trie_insert(&$trie, $path_segments, $index)
    {
        if (!isset($path_segments[$index])) {
            return $trie;
        }
        $segment = $path_segments[$index];

        if (strlen($segment) > 0 && $segment[0] === '*') {
            $node = self::trie_insert_wildcard_node($trie, $segment);
        } elseif (strlen($segment) > 0 && $segment[0] === ':') {
            $node = self::trie_insert_param_node($trie, $segment);
        } else {
            $node = self::trie_insert_static_node($trie, $segment);
        }
        return self::trie_insert($node, $path_segments, $index + 1);
    }
}

The ampersands are being removed from assignments like $x = &f(); where we want to bind a reference returned from a function to a variable, turning it into a normal, copying assignment, which breaks the code.

https://www.php.net/manual/en/language.references.return.php

bug

All 5 comments

Thanks for issue, should be fixed in master

This is indeed fixed and has just been released as part of v0.12.0.

Thank you! I can confirm it's fixed.

It looks like assigning by reference within an array to another array value might've broken during that change.

Works:

<?php
$test = ['key' => &$value];

Used to work but now doesn't (ampersand is removed):

<?php
$test = ['key' => &$value['something']];

A workaround for now is:

<?php
$test = [];
$test['key'] = &$value['something'];

On the current master even the first example is not printed correctly - thanks for reporting!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

czosel picture czosel  路  4Comments

bertuz picture bertuz  路  5Comments

czosel picture czosel  路  6Comments

Selion05 picture Selion05  路  4Comments

alexander-akait picture alexander-akait  路  5Comments