OK…
Hopefully this will answer your question. When scripting or coding, A function function to avoid repetition. A function can be use one time, an infinite number of times or not at all. Coders use the term “calling” when they use a function.
foo($arg){
if ($arg==0){ return;}
if ($arg==1){ return false;}
$modArg=$arg *2;
return “$modArg is 2x $arg”;
}
$a= foo(0);// null
$a =foo(1);// Boolean false
$a=foo(5);// string “10 is 2x 5”
- I can call foo(); as many times as needed.
- you will notice I used return 3times in the function. In a function the return statement ESCAPES the function and goes back to executing the code where it was called from.
- A “return” by itself does not pass any variable back…$a= foo(0);// null.
“thats useless”, you might say… but remember the function of a function is to keep you from having to type the same code over and over … So that means you may have OUTPUT FUNCTIONS… that is functions you use merely to calculate something then ECHO it.
foo($content $headline, $tag=1){
echo “<div class=‘part’><h$tag> $headline</h$tag>$content</div>”;
return;
}
you dont really want to send anything back to the main code you just want a variable output…in that example the return is merely a formality.
when you want something sent back… you use: return $functionvar;
$functionvar has to be a variable that inside the function. This is for the same reason that if you try to work with a variable from your main code within the function, without having passed it TO the function, by putting it in ()… you will get a variable not declared error. This is know as scope…
Ok so you sent a vaiable ( actually a copy of a variable) into the function… but you want to get data BACK out… you can send ONE result out of the function. Thats teh other thing return does it sends a variable or constant out…
return $var; // returns $var to the main code…
return 15; // returns 15 to the main code…
return true; // returns boolean true to the main code…
if you don’t have anything to cat the returned result it is lost. No biggie.
foo(2); // returned value is lost…
$a=foo(2); // whatever foo calculated is stored in $a
why not capture values all the time, you say? well thin about it a function can be ANYTHING… its just to keep you from typic code over and over…
so what if you wanted to check that the result of a value plugged into a formula is not 10, for example…
foo($agr){
$mathStuff=$arg/(2*11);
if ($mathStuff!=10) {return true);}
return false;}
if you follow the code… you will see that foo() will return Boolean true for any value that, when divided by 22 doesnt equal 10… and return Boolean false for anything else
you can use this directly in an if statement in the main code:
if (foo($argToTest)){ do something…}
see, a value you didnt need to capture and a use for returning booleans !
hope that makes things a little clearer