Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple function not woking

Status
Not open for further replies.

Trancemission

Technical User
Oct 16, 2001
108
GB
I have a problem which is driving me mad and need some direction. I am trying to use my own functions. I have the following test code which I fail to get working on the following configs:

Apache + Php [4.3,4.2]
IIS + Php [4.3]


<?
function add($num1, $num2, $result=0)
{
$result = $num1 + $num2;
echo $result; <------ THIS WORKS!
return $result;
}
add(1,2);
echo $result;
?>
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=iso-8859-1&quot;>
</head>

<body>
<?
echo &quot;<P>$result</P>&quot;;
?>
</body>
</html>

Surley this is simple code and should work? And I totally missing the point and do I need to rtfm? As you can see the $num2 + $num2 is working as it prints in the function.

I have tried not putting $result=0 in the function :)

Cheers
Trancemission
=============
If it's logical, it'll work!
 
It's a scoping issue... $result is ONLY set within your function... do this...

[red]function add($num1, $num2)[/red]

and

then when you call it

$result = add(1,2);

-Rob

 
or if you want the 3rd parameter to hold your return do this:

function add($num1, $num2, &$result=0)
{
$result = $num1 + $num2;
echo $result; <------ THIS WORKS!
return $result;
}

so add(1,2,$res); $res will hold 3 --BB
 
Then there's no reason to return $result... if you want to pass by reference then...

function add($num1, $num2, &$res)
{
$res = $num1=$num2;
}

add(1,2,$result);

is sufficient.

-Rob
 
Many Thanks for the replies, all is working fine now.

As a note, I will be setting session variables in my function. Will this work? I have a login function and if successful will set a session variable.

Many THanks Trancemission
=============
If it's logical, it'll work!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top