Re: Variables within functions, out?

From: Date: Fri, 02 Feb 2001 00:14:16 +0000
Subject: Re: Variables within functions, out?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-37758@lists.php.net to get a copy of this message
On Fri, 2 Feb 2001 08:51, James, Yz wrote: > Hey guys. Can I firstly say, thanks to all of you who helped me out with > my last question about importing MS Access databases into MySQL... It > helped tons! > > However, I have another question. > > Firstly, I've strayed away from writing many of my own functions, because > they give me the fear. But the code on the pages I am creating has > forced me to wake up... I really sould think about cutting back on code. > > SO, anyway, to cut to the chase, my question is this: If I write a > function, which performs checks and assigns variable based on these > checks, how do I get the assigned variables from within the function? > For example (this is more than likely VERY wrong), something like this: > > global.inc: > > <? > > function CheckBirthday() { > global $year,$month,$day; > > if (($day) && ($month) && ($year)) { > if (checkdate($day,$month,$year) { > $birthday = "$year/$month/$day"; > } else { > $birthday = "Invalid"; > } > } > } > > ?> > > File that would update / insert information to a MySQL database: > > <? > > // Connection details here > > require("global.inc"); > > CheckBirthday(); > > $sql = "UPDATE MyTable > SET > birthday = \"$birthday\" > WHERE id = \"$id\" > "; > > // etc > > ?> > > Even when I KNOW that I have included correct values, the $birthday > variable never shows up outside the function. It's probably something > simple I'm missing, as in most cases ;) > > Thanks for your patience, > > James. The specific answer to your question is that the variable $birthday is local to the function - check out variable scope in the manual. But in fact there is another way of doing it - pass the values to check as parameters to the function and have it return a result, thus: function CheckBirthday($year,$month,$day) { if (($day) && ($month) && ($year)) { if (checkdate($day,$month,$year) { $birthday = "$year/$month/$day"; } else { $birthday = "Invalid"; } } return $birthday } and to use it: $result = CheckBirthday($year,$month,$day); $sql = "UPDATE MyTable SET birthday = \"$result\" WHERE id = \"$id\" "; Those " around the variables probably should be ' if you are playing with mysql char fields. -- David Robley | WEBMASTER & Mail List Admin RESEARCH CENTRE FOR INJURY STUDIES | http://www.nisu.flinders.edu.au/ AusEinet | http://auseinet.flinders.edu.au/ Flinders University, ADELAIDE, SOUTH AUSTRALIA

« previous php.general (#37758) next »