Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function via reference

I need to recursivly echo comments and their respective children from a Jelly collection in Kohana. I was wondering how I pass a variable to a function via reference. I assume it would be something like this:

function recursive(&$array)
{
    recursive(&$array);
}

But I am not quite sure. So is this correct or when I call the function do I not need the ampersand?

Thanks.

like image 924
Olical Avatar asked Dec 28 '22 06:12

Olical


1 Answers

You don't need the ampersand when you call the function because you have already declared it to accept a reference as a parameter using the ampersand.

So you would just write this:

function recursive(&$array)
{
    recursive($array);
}

On a side note, generally you should avoid adding the ampersand to function calls. That is called call-time pass-by-reference. It's bad because the function may be expecting a parameter to be passed by value, but you're passing a reference instead so in a way you're screwing with the function without it knowing. As I have said above, a function will invariably take a parameter by reference if you declare it as such. That therefore makes call-time pass-by-reference unnecessary.

In PHP 5.3.0 and newer, call-time pass-by-reference causes PHP to emit E_DEPRECATED warnings as it has been deprecated (rightfully so).

like image 196
BoltClock Avatar answered Jan 11 '23 23:01

BoltClock