Is it a good idea to create variables using references?

Example:

function create_pets(&$cats, &$dogs){ $dogs = get_dogs(); $cats = get_cats(); } 

so I would call it the following:

 function foo(){ create_pets($cats, $dogs); // here use $cats and $dogs variables normally } 

I know that I can simply assign a new variable the return value of one of these getter functions, but this is just an example. In my situation there is more than just a getter ...

+4
source share
2 answers

The answer, as everyone says, is "it depends." In your specific example, the β€œcreate” function, the code is less obvious for operation and maintenance, and therefore it is probably a good idea to avoid this pattern.

But here is the good news, there is a way to do what you are trying to do, which makes things simple and compact without using links:

 function create_pets(){ return array(get_dogs(), get_cats()); } function foo(){ list($dogs, $cats) = create_pets(); //here use $cats and $dogs variables normally } 

As you can see, you can simply return the array and use the list language construct to get the individual variables on the same line. It’s also easier to say what happens here, create_pets () will obviously return the new $ cats and $ dogs; the previous method using links did not make this clear if only one verified create_pets () was not directly.

You will not find a difference in performance when using either method, although both will work. But you will find that the recording code, which is easy to track and operate, ultimately goes a long way.

+1
source

It depends on the circumstances. Most of the time you usually call variables by value, but in certain situations, when you want to change the contents of variables without changing the value of the variable in other parts of the code, then calling by reference is a good idea. Another reasonable if you want only actual content, and only actual content, and then call by value is the best idea. This link explains this very well. http://www.exforsys.com/tutorials/c-language/call-by-value-and-call-by-reference.html

+1
source

All Articles