Caryn May
Caryn May

Reputation: 13

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?

Upvotes: 1

Views: 402

Answers (1)

Geshode
Geshode

Reputation: 3764

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;

Upvotes: 2

Related Questions