Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php using '&' operator [duplicate]

Tags:

operators

php

Possible Duplicate:
Reference - What does this symbol mean in PHP?

hi i have trouble to understand some of the & operator usage. i have come across with multiple examples and point out only those whitch i dont know what they really do ...

what does it mean when i'm:

1) using & in function name

function &foo() {}

2) using & in function parameter

function foo($id, &$desc) {}

3) usgin & in loop

foreach ($data as $key => &$item) {}
like image 959
nabizan Avatar asked Jan 18 '11 08:01

nabizan


People also ask

What is PHP use?

PHP(short for Hypertext PreProcessor) is the most widely used open source and general purpose server side scripting language used mainly in web development to create dynamic websites and applications.

What is use in PHP with example?

The use keyword has two purposes: it tells a class to inherit a trait and it gives an alias to a namespace.

What is Namespacing in PHP?

Namespaces are qualifiers that solve two different problems: They allow for better organization by grouping classes that work together to perform a task. They allow the same name to be used for more than one class.


2 Answers

function &foo() {}

Returns a variable by reference from calling foo().

function foo($id, &$desc) {}

Takes a value as the first parameter $id and a reference as the second parameter $desc. If $desc is modified within the function, the variable as passed by the calling code also gets modified.

The first two questions are answered by me in greater detail with clearer examples here.

And this:

foreach ($data as $key => &$item) {}

Uses foreach to modify an array's values by reference. The reference points to the values within the array, so when you change them, you change the array as well. If you don't need to know about the key within your loop, you can also leave out $key =>.

like image 50
BoltClock Avatar answered Oct 21 '22 23:10

BoltClock


The PHP manual has a huge section on references (the & operator) explaining what they are and how to use them.

In your particular examples:

1) Is a return by reference. You need to use the & when calling the function and when declaring it, like you have above: Return by Reference

2) Is passing a parameter by reference. You only need to use the & in the function definition, not when calling the function: Passing by Reference

3) Is using a reference in a foreach loop. This allows you to modify the $item value within the originating array when you're inside the loop.

All the complete information on PHP references is available in the manual.

like image 23
Jamie Hurst Avatar answered Oct 21 '22 22:10

Jamie Hurst