PHP function returns 0, not sure why
Here is the PHP im working with:
Below values from a database:
$quote = 49;
$add_amp = 0;
$con_array = "3,2,1";
function calcAddAmp($mul)
{
$add_amp = $add_amp + $mul*($quote);
}
$con_array = explode(",", $con);
for($i = 0; $i < count($con_array); $i++) {
switch ($fun) {
case 1:
calcAddAmp(.01);
break;
case 2:
calcAddAmp(.05);
break;
case 3:
calcAddAmp(.02);
break;
case 4:
calcAddAmp(.09);
break;
}
}
$quote = $quote + $add_amp;
The issue is seen here:
echo $add_amp;
$add_amp returns 0, which makes $quote the same value as before, 49.
echo $quote;
I'm sure I 开发者_如何学运维am just writing this function incorrectly, but I can't find where I went wrong.
Variables have function scope. Setting $add_amp
inside a function does not automatically modify the variable by the same name outside the function. If you don't return
the value from the function it's pointless. I'd simplify this whole unnecessary switch
/function
to this though:
$multipliers = array(1 => .01, 2 => .05, 3 => .02, 4 => .09);
foreach ($con_array as $con) {
$add_amp += $multipliers[$con] * $quote;
}
$add_amp
is declared outside of your function.
If you want to modify the global one, you need to change your function like this:
function calcAddAmp($mul)
{
global $quote;
global $add_amp;
$add_amp = $add_amp + $mul * $quote;
}
It would be even better to just return the value from your function:
function calcAddAmp($mul,$a,$q)
{
return $a + $mul * $q;
}
$add_amp = calcAddAmp(0.5,$add_amp,$quote);
Use the global keyword in the function. And your switch is wrong $fun is not defined.
The $add_amp
is a local variable in the function. It will be reassigned every time you call the function, and the $add_amp
variable that you created at the top will always be 0.
Here is another approach, by using reference:
function calcAddAmp(&$add_amp, $mul)
{
global $quote;
$add_amp += $mul*($quote);
}
example of usage:
calcAddAmp($add_amp, 0.5);
Quote and add_amp need to be global.
global $quote;
global $add_amp;
$quote = 49;
$add_amp = 0;
$con_array = "3,2,1";
function calcAddAmp($mul)
{
global $quote;
global $add_amp;
$add_amp = $add_amp + $mul*($quote);
}
for($i = 0; $i < count($con_array); $i++) {
switch ($fun) {
I think you meant:
for($i = 0; $i < count($con_array); $i++) {
switch ($con_array[$i]) {
Otherwise your cases never match (as $fun
doesn't exist), calcAddAmp
is never called and $add_amp
's value never changes.
You will also need to be sure to use the global $add_amp
and $quote
in calcAddAmp
, as at the moment you're operating on some new local ones with the same name:
function calcAddAmp($mul) {
global $add_amp, $quote;
$add_amp += $mul * $quote;
}
or
function calcAddAmp($mul) {
$GLOBALS['add_amp'] += $mul * $GLOBALS['quote'];
}
It would be better to avoid globals entirely, and pass these variables where they are required as function parameters.
精彩评论