Reputation: 3482
I have a simple function like so which I use to compare something,
function life($life) {
while($life) {
echo $life . '<br />';
--$life;
}
return $life;
}
$life = life($user['lifeforce']);
if($life) { ... }
Should I pass it by reference or forget it and use what I am using? Would it be better to do...
function life(&$life) {
while($life) {
echo $life . '<br />';
--$life;
}
}
life($user['lifeforce']);
if($user['lifeforce']) { ... }
I am not quite understading the concepts of passing by reference?
Thanks
Upvotes: 0
Views: 49
Reputation: 21007
At first make sure that you read php manual on references, especially the part about passing by reference.
Simple example:
function integer_division( $number, $divider, &$remain){
$remain = $number%$divider;
return floor( $number/$divider);
}
$remain = 0;
$result = integer_division( 5, 2, $remain);
// $remain now contains 1
You should use reference ONLY when you intend to change value original variable (for example array sort functions work that way), or you need to return more than 1 value (and returning an array is a bad option).
So to answer your question directly: you should probably use the first way (unless you want to have 0 in userlife).
Upvotes: 1