Page 1 of 1
Getting stuff out of a function
Posted: Fri Mar 30, 2007 8:16 am
by Pezmc
I am not a newbie I have just never figured out how to do this (taught my self php).
I have a function say
Code: Select all
function socks(test,sock) {
echo $test
echo "I am a fary:"
echo $sock
$total = $test * $sock;
}
How can I get the total out of the function to use in other places as a variable, is there a returning function or something?
Posted: Fri Mar 30, 2007 8:20 am
by Begby
Code: Select all
function multiply($x, $y)
{
return $x * $y ;
}
$result = multiply(10, 9) ;
You are not a newbie and didn't know that? Good lord, if you have been writing a ton of code without using function returns then you are one hard core dude.
Perhaps a book like Learing PHP from O'Reilly press would be a good idea. Just spend 15 minutes a day with it on the toilet and you will learn a lot of stuff that will make your coding life a lot easier.
Posted: Fri Mar 30, 2007 8:21 am
by feyd
The keyword "return"...
Posted: Fri Mar 30, 2007 8:35 am
by Pezmc
Begby wrote:Code: Select all
function multiply($x, $y)
{
return $x * $y ;
}
$result = multiply(10, 9) ;
You are not a newbie and didn't know that? Good lord, if you have been writing a ton of code without using function returns then you are one hard core dude.
Perhaps a book like Learing PHP from O'Reilly press would be a good idea. Just spend 15 minutes a day with it on the toilet and you will learn a lot of stuff that will make your coding life a lot easier.
Lol thanks yeh I have mainly been using c&p for all of the functions. I have written quite a few website with out it. Is it possible to use
or do I need to do
Code: Select all
return $socks;
return $dogs;
return $etc;
Thanks for your help this will make my life alot easier in the future
Posted: Fri Mar 30, 2007 8:43 am
by Begby
You can only return one thing at a time. As soon as you hit the first return the function is immediately exited with no other code in that function executed.
To return multiple items you will either need to return an array, return an object, or pass parameters to the function by reference and change their values.
Edit: Haha, I type quicker than Feyd
|
|
V
Posted: Fri Mar 30, 2007 8:44 am
by feyd
Neither are usable. To return multiple values you use an array. Functions can only return one thing. That one thing may contain other things, but the function itself can only return one thing.
Posted: Fri Mar 30, 2007 8:53 am
by onion2k
As has been said, functions can only return one thing (eg an array), but you can work around that with list()..
Code: Select all
function myFunction() {
$item = "Lawnmower";
$make = "Honda";
$color = "Red";
return array($item,$make,$color);
}
list($item,$make,$color) = myFunction();
echo "I want a ".$color." ".$make." ".$item;
Silly example because you'd be better off with an object in this case, but it demonstrates using list().