Now, all this is well and good, but it's not exactly setting the house on fire, is it? Well, there are a couple of things you need to add into the mix for your user-defined functions to actually start earning their keep: return values and function arguments. Usually, when a function is invoked, it generates a "return value" - this may be value of the last expression evaluated, or a value explicitly returned to the main program via the "return" statement. Our next example demonstrates how a return value works: The output of the script above has not changed; however, there are significant differences in the manner of its execution. In the example above, the functions do not provide any output - they simply assign a string to the variable $answer. When the function is invoked, it passes the value of this variable to the main program, where it is assigned to the variable $response and displayed on the page. And just as a PHP function can return values *to* the main program, it can also accept "function arguments" *from* the main program. Take a look: The first thing you should notice here is that the function definition has changed - the parentheses, which seemed to be there only for decorative purposes, now enclose two PHP variables called $alpha and $beta. When arguments are passed to the function, they will be stored in these PHP variables for the duration of the function and can be further acted upon by the statements within the function. In the example above, $num1 (9) and $num2 (16) are the two arguments passed to the function multiply() The function multiply() accepts the two arguments, performs a mathematical operation on them, stores the result in $product and returns $product to the main program as $answer. Here's the output: The multiply() function can be used with any pair of numbers - as the arguments passed to it change, so will the result. This is how functions allow you to re-use the same piece of code over and over again, without any need to re-write code each time.{mospagebreak title=Flavour Of The Month} An important point to be noted here is that it isn't possible to use variables outside the function within the function definition...unless you use the special "global" keyword. This keyword, when used within a function, allows you to use a variable from outside the function within the function as well. To illustrate this, consider the following two examples: Here's the output: And here's what you need to do to make the variable a global variable: Here's the output:
blog comments powered by Disqus |