PHP 5.4 Call-time pass-by-reference - How to fix it?
Asked Answered
F

1

0

I have the problem that I get the error

PHP Fatal error: Call-time pass-by-reference has been removed in....

I discovered some similar questions e.g.

But nothing offers a reals answers how situations be can solved where you NEED to declare the passed value as refference by runtime for e.g. buildin function which you cant change function declaration ??.

e.g. for this example third array_walk parameter as reference: ?

I tried to use this solution to change the indexes of my array with this code:

function __reindex(&$v,$k, &$aReindexed) 
{ 
   $kNew = $k+100;
   $aReindexed[$kNew] = $v; 
}


$aTest = array(4,"f","_","test");
array_walk($aTest,"__reindex", &$aReindexed );

The Code without the refference is not working (the new array is not changed and stays empty).

And the Code with the refference it works, but not in php 5.4 and higher.

So whats the way so handle such situations ?

p.s. if anybody likes to say "declare the $k variable in your __reindex function as refference" then that wont work (that was the first way I tried)

Feme answered 6/12, 2019 at 13:16 Comment(0)
F
0

I found a way what maybe helps some people.

Try this Code

$aTest = array(4,"f","_","test");
$aReindexed = array();

array_walk($aTest, function(&$v,$k) use (&$aReindexed) { 
  $kNew = $k+100;
  $aReindexed[$kNew] = $v; 
} );

print_r($aReindexed);

This coud would work in php 5.4 and above.

But it works not for lower php versions, and you can not use it with an already existing (non-anonym) callback function, because the USE-Keyword only works when you create a new Closure function.

Feme answered 6/12, 2019 at 13:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.