Getting an undefined variable error for variable defined within function in php

405 views Asked by At

I have the following code:

$SpeedA = 5; 
$SpeedB = 5; 
$Distance = 20; 

function CalDistance ($SpeedA, $SpeedB, 
$Distance)
{
    $DistanceA = (($SpeedA / $SpeedB) * 
    $Distance) / (1 + ($SpeedA / $SpeedB));

    Return $DistanceA;

}
echo $DistanceA;

I get this error:

Notice: undefined variable $DistanceA

Why $DistanceA is regarded as undefined and how to fix it?

1

There are 1 answers

2
Geshode On BEST ANSWER

You never call the function CalDistance, before your echo. So, you try to echo an undefined $DistanceA.

So, you could do something like this:

$SpeedA = 5; 
$SpeedB = 5; 
$Distance = 20; 

function CalDistance ($SpeedA, $SpeedB, 
$Distance)
{
    $DistanceA = (($SpeedA / $SpeedB) * 
    $Distance) / (1 + ($SpeedA / $SpeedB));

    Return $DistanceA;

}

$call = CalDistance($SpeedA, $SpeedB, $Distance);
echo $call;