Re: array_walk_recursive pass by reference

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Sun, Aug 29, 2010 at 12:35 AM, kranthi <kranthi117@xxxxxxxxx> wrote:

> i have an array
> $parms = array('1' => 'a', 'b' => array(3 => 'test'));
> i want $mail = '1:a 3:test';
>

But you're uppercasing and adding new lines and additional spaces, so I hope
you want (at least, this is what I tested against):

"1: A\n3: Test\n"


>
> array_walk_recursive($parms, function($val, $key, &$mail) {
>     $mail .= ucwords($key) . ': '. ucwords($val) . "\n";
> }, &$mail);
>

This worked just as you said.


>
> The above function worked perfectly well
> but i am getting: Call-time pass-by-reference has been deprecated in
> /var/www/html/test.php on line 31
>
> if i change it to
>
> array_walk_recursive($parms, function($val, $key, &$mail) {
>    $mail .= ucwords($key) . ': '. ucwords($val) . "\n";
> }, $mail);
>
> i am not getting the error but $mail is not being returned.
>

This failed just as you said.

Note, the function signature does not say userdata is passed by reference.
 So, by the time your function is called, the original reference has already
been lost and your function is getting a reference to a copy (bummer, I
know.)

bool *array_walk_recursive* ( array &$input ,
callback<language.pseudo-types.php#language.types.callback>
 $funcname [, mixed <language.pseudo-types.php#language.types.mixed>
$userdata ] )


>
> ny solution ?
>
>
For a quick fix, I'd use an object, which is pass by reference by nature:

class StringWrapper {
public $string = '';
}

$mail = new StringWrapper();

array_walk_recursive($parms, function($val, $key, $mail) {
   $mail->string .= ucwords($key) . ': '. ucwords($val) . "\n";
}, $mail);

if ($mail->string == "1: A\n3: Test\n") {
echo 'Yes, this worked';
} else {
echo 'No, not again.';
}

You could also use a static method from a class and forget about passing the
$userdata variable, or use a static variable within the function itself to
maintain state.

That said, I've had several situations where I would have preferred the ease
of passing the userdata argument by reference, so I feel your pain.

Adam

-- 
Nephtali:  PHP web framework that functions beautifully
http://nephtaliproject.com

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux