RE: [PHP] return

From: Date: Mon, 16 Jul 2001 20:35:46 +0000
Subject: RE: [PHP] return
Groups: php.general 
Request: Send a blank email to php-general+get-58113@lists.php.net to get a copy of this message
> Here's my code: > <? > function expDate($date) { > $month = substr("$date", 0, 2); > $len = strlen($date); > $year = substr("$date", $len-2, $len); > return $month; > return $year; > } > expDate("11/2002"); > print "$month $year"; > ?> > I know this isn't the correct usage of return, but how to I > get the $month and $year variables so I can print them > after I've called the expDate() function? Currently, nothing > is printed to the browser. You cannot use "return" twice like that. The function will exit immediately after the first valid "return" call it hits. To do what you want, you can do this: ---------------- function expDate($date, $returnMonth, $returnYear ) { $month = substr("$date", 0, 2); $len = strlen($date); $year = substr("$date", $len-2, $len); $returnMonth = $month; $returnYear = $year; } $month = 0; $year = 0; expDate( "11/2002", &$month, &$year ); print "$month $year"; -------------- The "&" operator passes a variable by reference. Alternately, you can do: ---------------- function expDate($date, $returnMonth, $returnYear ) { global $month; global $year; $month = substr("$date", 0, 2); $len = strlen($date); $year = substr("$date", $len-2, $len); } $month = 0; $year = 0; expDate( "11/2002" ); print "$month $year"; -------------- Though, I try to use "global" as little as possible. Chris

« previous php.general (#58113) next »