Search code examples
phpundefined-variable

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


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?


Solution

  • 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;