按引用或按变量的函数,什么时候使用? [英] Functions by reference or by variable, which to use when?

查看:38
本文介绍了按引用或按变量的函数,什么时候使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗯,我在我的 PHP 手册中读到,能够区分引用参数和变量参数非常重要.书中说,当变量改变时,参数化变量的原始值被保留,而当引用改变时,参数化引用的原始值发生变化.如果我没看错的话,这就是关键的区别.

Well, I read in my handy PHP book that it's very important to be able to distinguish between reference and variable parameters. The book says that the original value of parameterized variables are preserved when the variable is changed, and the original values of parameterized references change when the reference is changed. It says that's the key difference, if I am reading right.

嗯,我想知道什么时候每个都比另一个更有用.创建自己的函数时,如何知道何时使用变量以及何时使用引用?

Well, I'm wondering when each is more useful than the other. How do I know when to use variables and when to use references when I create my own functions?

推荐答案

引用"(变量别名)使您的代码更难理解,并可能成为难以跟踪错误的根源.没有正当理由在 php 中使用引用,为了安全起见,尽量避免使用引用.

"References" (variable aliases) make your code harder to understand and could be a source of hard to follow errors. There are no valid reasons to use references in php and to be on the safer side try to avoid them altogether.

不,php5 中的对象与引用"无关.

And no, objects in php5 have nothing to do with "references".

在 php 中实现的引用"是一个奇怪的概念.通常,在编程语言中,变量是相互独立的,因此更改一个变量不会影响其他变量.PHP引用"允许多个变量共享相同的值并相互依赖.基本上,你改变了一个变量,突然间另一个你认为完全不相关的变量也发生了变化.这不是什么好事,经常会导致很多混乱.

"References" as implemented in php is a strange concept. Normally, in programming languages variables are independent of each other so that changing one variable doesn't affect others. Php "references" allow several variables to share the same value and to be dependent of each other. Basically, you change one variable, and suddenly another one, which you think is totally unrelated, is getting changed too. It's no good thing and often leads to much confusion.

php 中的对象(我需要添加五个"吗?)与上述意义上的引用"无关.它们的行为很像 C 指针(实际上,这就是它们的内幕)——当你将一个对象传递给一个函数时,你实际上传递了一个指针,函数可以使用这个指针来操作对象内容,但没有函数改变传递的变量本身的方式,例如,使它指向另一个对象.

Objects in php (do I need to add 'five'?) have nothing to do with "references" in the above sense. They behave much like C pointers (actually, this is what they are under the hood) - when you pass an object to a function, you actually pass a pointer, and the function can use this pointer to manipulate the object contents, but there's no way for the function to change the passed variable itself, for example, make it point to another object.

这种对象是引用"的误解可能是因为人们将 php引用"(与号语法)与 通用 CS 术语,也适用于指针、句柄等

This "objects are references" misunderstanding is probably because people confuse php "references" (ampersand syntax) with the generic CS term , which also applies to pointers, handles etc.

这篇关于按引用或按变量的函数,什么时候使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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