通过引用递归函数
我需要从 Kohana 的 Jelly 集合中递归地回显评论及其各自的子项。我想知道如何通过引用将变量传递给函数。我认为它会是这样的:
function recursive(&$array)
{
recursive(&$array);
}
但我不太确定。那么这是正确的还是当我调用该函数时我不需要&符号?
谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
调用该函数时不需要使用 & 符号,因为您已经使用 & 符号将其声明为接受引用作为参数。
因此,您只需这样写:
顺便说一下,通常您应该避免在函数调用中添加“&”符号。这就是所谓的调用时间引用传递。这是坏,因为函数可能期望参数按值传递,但您却传递了一个引用,因此在某种程度上您在不知不觉中破坏了函数。正如我上面所说,如果您这样声明,函数将始终通过引用获取参数。因此,这使得调用时不需要通过引用传递。
在 PHP 5.3.0 及更高版本中,调用时传递引用会导致 PHP 发出
E_DEPRECATED
警告,因为它已被弃用(理所当然)。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:
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).