何时在PHP中通过引用传递 [英] When to pass-by-reference in PHP

查看:72
本文介绍了何时在PHP中通过引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道当您仅读取变量时,按引用传递的优良作法还是应该始终将其作为值传递.

Im wondering if its good practice to pass-by-reference when you are only reading a variable, or if it should always be passed as a value.

带有引用传递的示例:

$a = 'fish and chips';
$b = do_my_hash($a);
echo $b;

function &do_my_hash(&$value){
   return md5($value);
}

传递值的示例:

$a = 'fish and chips';
$b = do_my_hash($a);
echo $b;

function do_my_hash($value){
   return md5($value);
}

哪个更好?例如,如果我要运行1000次循环?

Which is better ? E.g if I was to run a loop with 1000 rounds ?

循环示例:

for($i = 0 ; $i < 1000 ; $i++){
   $a = 'Fish & Chips '.$i;
   echo do_my_hash($a);
}

推荐答案

如果您打算传递 (因此该函数不会对其进行修改),没有理由通过引用传递它:它只会使您的代码更难理解,因为人们会认为"此函数可以修改我将传递给它的内容—哦,它不会对其进行修改?"

If you mean to pass a value (so the function doesn't modify it), there is no reason to pass it by reference : it will only make your code harder to understand, as people will think "this function could modify what I will pass to it — oh, it doesn't modify it?"

在您提供的示例中,您的do_my_hash函数不会修改您要传递给它的 value ;所以,我不会使用参考.

In the example you provided, your do_my_hash function doesn't modify the value you're passing to it; so, I wouldn't use a reference.

如果您担心性能,则应该阅读以下最新博客文章:

And if you're concerned about performance, you should read this recent blog post: Do not use PHP references:

人们使用参考的另一个原因是 因为他们认为这使代码 快点.但这是错误的.甚至 更糟的是:引用大多使代码 慢点!是的,参考经常 代码变慢-对不起,我只需要 重复此操作以使其清楚.

Another reason people use reference is since they think it makes the code faster. But this is wrong. It is even worse: References mostly make the code slower! Yes, references often make the code slower - Sorry, I just had to repeat this to make it clear.

实际上,即使您并不主要关注性能,这篇文章也可能是有趣的文章;-)

Actually, this article might be an interesting read, even if you're not primarily concerned about performance ;-)

这篇关于何时在PHP中通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆