Page 1 of 1

Problem in Calling Function in PHP

Posted: Mon Mar 09, 2009 11:06 am
by Akirien
My code is like this :

<?php
$A=$_GET['name'];
$B=$_GET['memberno'];
$C=$_GET['member'];
$D=$_GET['points'];
function display()
{
echo "<b>Customer Name :</b> $A<br>";
echo "<b>Membership No. :</b> $B<br>";
echo "<b>Membership Type :</b> $C<br>";
echo "<b>Point in hand :</b> $D<br>";
echo "<b>Additional Point :</b> $addpoint<br>";
echo "<b>Total point :</b> $total<br>";
}
echo "<b><u>Online Shopping Point</u></b><br><br><br>";
if($C=='Basic')
{
if($D>=0 AND $D<=250)
{
$addpoint = 0.05 * $D;
$total = $addpoint + $D;
display();

}
else
{
if($D>250 AND $D<501)
{
$addpoint = 0.075 * $D;
$total = $addpoint + $D;
display();
}
}
}
?>


THE PROBLEM IS...when I call the funtion...the value did not come out.
How to make it comes out?

Re: Problem in Calling Function in PHP

Posted: Mon Mar 09, 2009 12:03 pm
by susrisha
1. Post in appropriate tags please
2. you are trying to call global variables inside a function.
here is an example of how yo use it

Code: Select all

 
$a='hello';
function somefunc()
{
global $a;
echo "the value of a is ".$a;
}
 

Re: Problem in Calling Function in PHP

Posted: Mon Mar 09, 2009 12:06 pm
by Akirien
susrisha wrote:1. Post in appropriate tags please
2. you are trying to call global variables inside a function.
here is an example of how yo use it

Code: Select all

 
$a='hello';
function somefunc()
{
global $a;
echo "the value of a is ".$a;
}
 
8O ....thank you..I am new..sorry if i have made some mistakes.
:)

Re: Problem in Calling Function in PHP

Posted: Mon Mar 09, 2009 12:16 pm
by susrisha
to err is human :) .. you wont learn untill you know what you are doing is wrong ;)
lots of philosophy hehe..

Re: Problem in Calling Function in PHP

Posted: Mon Mar 09, 2009 1:03 pm
by John Cartwright
It is generally not a good idea to use global variables because variables can be manipulated in different scopes.

It is more advisable to pass the variables as parameters to the function to keep the variables in scope and it also defines a clear interface to the function.

Code: Select all

function display($name, $memshipno, $type, $points, $addpoint, $total)  
{
   $format = "
      <b>Customer Name :</b> $name<br>
      <b>Membership No. :</b> $memshipno<br>
      <b>Membership Type :</b> $type<br>
      <b>Point in hand :</b> $points<br>
      <b>Additional Point :</b> $addpoint<br>
      <b>Total point :</b> $total<br>
    ";
 
   return $format;
}
Lastly, while not as important, I've found it is better to have a return value for the function instead of directly echo'ing because it makes it more flexible. Then it would be a simple matter of

Code: Select all

echo display( ... );