PHP 引用在 Laravel 宏中不起作用

PHP references doesn't work in Laravel macros

尝试在不使用引用的情况下 return 为数组创建一个将键替换为给定值的辅助方法,但它不起作用。

Arr::macro('replaceKey', function (string $from, string $into, array &$inside) {
    if (! array_key_exists($from, $inside)) {
        throw new Exception("Undefined offset: $from");
    }

    $inside[$into] = $inside[$from];

    unset($inside[$from]);
});

用 trait 和简单的函数尝试了同样的事情,它起作用了。

// inside trait

public function replaceKey(string $from, string $into, array &$inside)
{
    if (! array_key_exists($from, $inside)) {
        throw new Exception("Undefined offset: $from");
    }

    $inside[$into] = $inside[$from];

    unset($inside[$from]);
}

谁能解释为什么?

你得到的是空值,因为你没有从函数返回任何东西。

public function replaceKey(string $from, string $into, array &$inside)
{
    if (! array_key_exists($from, $inside)) {
        throw new Exception("Undefined offset: $from");
    }

    $inside[$into] = $inside[$from];

    unset($inside[$from]);
    return $inside;
}

还有宏

Arr::macro('replaceKey', function (string $from, string $into, array &$inside) {
    if (! array_key_exists($from, $inside)) {
        throw new Exception("Undefined offset: $from");
    }

    $inside[$into] = $inside[$from];

    unset($inside[$from]);
  
  return $inside;
});

当你调用宏时,在你的匿名函数被调用之前有一个方法调用; __callStatic 被调用。这需要一个方法名称和一个传递给方法调用的参数数组。

无法从该方法的方法签名端 __callStatic 声明参数数组的元素是一个引用,因为它只接收传递的所有参数的数组给不存在的方法 replaceKey 作为参数。

您正在获取对要传递给匿名函数中的宏方法调用的数组副本的引用。