TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   User defined function with 'return' statement -- not working (http://www.talkphp.com/absolute-beginners/2638-user-defined-function-return-statement-not-working.html)

Dave 04-15-2008 05:59 PM

User defined function with 'return' statement -- not working
 
This example is from a book that I'm using to learn, but I can't get it to work properly! What am I doing wrong here? I may have copied something wrong, but I've spend a couple of hours trying to figure it out...? :-/

php Code:
// Charge for an item.
   $nCharge = 100.00 ;
   
   // Define the function.
   function salestax($nCharge, $nShip = .10)
   {
      $nYourtotal = ($nCharge + ($nCharge * $nShip));
      return $nYourtotal ;
   }

   // Invoke the function...
   salestax($nCharge) ;

   // Print the results...
   print $nYourtotal ;

Thanks for any help...
Dave

wGEric 04-15-2008 06:09 PM

PHP Code:

<?php
   
// Charge for an item.
   
$nCharge 100.00 ;
   
   
// Define the function.
   
function salestax($nCharge$nShip .10)
   {
      
$nYourtotal = ($nCharge + ($nCharge $nShip));
      return 
$nYourtotal ;
   }

   
// Invoke the function...
   
$nYourtotal salestax($nCharge) ;

   
// Print the results...
   
print $nYourtotal ;

?>

You are returning the variable correctly. All you needed to do was assign the variable when you call the function. It was returning the value but it wasn't being stored or used in anyway.

Wildhoney 04-15-2008 06:12 PM

The only segment that I have modified is assigned the value of the salestax function to the $nYourtotal variable. When you issue the return in your custom function, that simply returns data back, and so you can either assign (as in our case), print (as we do later on when we print), or do nothing with (as you were doing previously).

php Code:
// Charge for an item.
$nCharge = 100.00 ;

// Define the function.
function salestax($nCharge, $nShip = .10)
{
    $nYourtotal = ($nCharge + ($nCharge * $nShip));
    return $nYourtotal ;
}

// Invoke the function...
$nYourtotal = salestax($nCharge) ;

// Print the results...
print $nYourtotal ;

Dave 04-15-2008 07:15 PM

Thanks to you both, Eric and Wildhoney! I see now that I am blocking on a basic concept related to UDFs, which I will write about (ask about!) in a different post.

Dave


All times are GMT. The time now is 04:07 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0