Functions by reference or by variable, which to us

2019-06-04 08:36发布

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?

2条回答
地球回转人心会变
2楼-- · 2019-06-04 09:15

It's pretty straightforward. Use references when you need to modify the value of the variable passed in to the function. Use variables when you don't need to or want to modify the value.

So, for example, if you're writing a function that takes an array and changes that array, you'd be better off using a reference for that array rather than returning a new array from the function.

查看更多
Root(大扎)
3楼-- · 2019-06-04 09:17

"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.

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

"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.

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.

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.

查看更多
登录 后发表回答