試圖為陣列創建一個輔助方法,將鍵替換為給定值而不使用參考回傳,但它不起作用。
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 和 simple function 嘗試了同樣的事情,它的作業原理。
// 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]);
}
誰能解釋為什么?
uj5u.com熱心網友回復:
當您呼叫宏時,在您的匿名函式被呼叫之前有一個方法呼叫;__callStatic被呼叫。這需要一個方法名稱和一個傳遞給方法呼叫的引數陣列。
不可能從該方法的方法簽名側__callStatic宣告引數陣列的元素是參考,因為它只接收傳遞給不存在的方法的所有引數的陣列replaceKey作為引數.
您將獲得對傳遞給匿名函式中的宏方法呼叫的陣列副本的參考。
uj5u.com熱心網友回復:
你得到 null 因為你沒有從函式中回傳任何東西。
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;
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/365841.html
上一篇:在多維陣列中搜索值
