Jump to content

What does the ampersand sign in front of a function name do?


colbyg

Recommended Posts

Return a reference.

<?php
function &testFunction(&$testReference) {
return $testReference;
}

$test = 'hello';

$reference =& testFunction($test);
$reference = 'world';

echo $test . ' ' . $reference;

 

The above code does not output "hello world", it outputs "world world" because testFunction returned a reference to $test. It doesn't appear particularly useful in this circumstance, but it can be quite useful in some situations.

Wow never knew PHP could do that >.<.

 

I'd imagine it was more useful in php4 when all classes weren't passed by reference automatically. Although I suppose it could be useful to retrieve references to certain array elements so that they can be modified. Something like...

 

<?php
function &findValue(&$array, $search, &$found = false) {
foreach($array as &$valRef) {
	if($valRef == $search) {
		$found = true;
		$result =& $valRef;
		break;
	}
	elseif(is_array($valRef)) {
		$result =& findValue($valRef, $search, $found);
		if($found) break;
	}
}

if($found) {
	return $result;
}
else {
	return $found;
}
}

$array = array(
'Hello',
'World',
array(
	'DeeperHello',
	'DeeperWorld'
)
);

$result =& findValue($array, 'DeeperHello', $found);
if($found) {
$result = 'ModifiedDeeperHello';
}
print_r($array);

/*
Array
(
    [0] => Hello
    [1] => World
    [2] => Array
        (
            [0] => ModifiedDeeperHello
            [1] => DeeperWorld
        )

)
*/

 

Of course it's messy, but you get the idea. I haven't used it before, but you never know.

ahh i got it

 

<?php
$array = array('Colby','Evan');
function &test() {
global $array;
return $array[0];
}

$test =& test();

$test = 'Tammy';

echo $array[0]; // prints 'Tammy'
?>

 

thank yall!

 

now i'll be late for school because i was doing this instead of getting ready

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.