PHP for the World Wide Web (Visual QuickStart Guide)
I l @ ve RuBoard |
Although being able to create a simple function is useful, writing one that takes input and does something with that input is even better. The input a function takes is called an argument and there are no limits to how many arguments a function can take. Functions that take arguments is a concept you've seen before: the print() function takes a string as an argument which it then sends to the browser. The syntax for writing functions that take arguments is as follows : function FunctionName ($Argument1, $Argument2, etc.) { statement(s); } Script 9.3. The existing hello.php page creates a customized greeting over several lines of code within the rest of the page.
These arguments will be in the form of variables which get assigned the value sent to the function when you call it. Functions that take input are called much like those which do not, you just need to remember to pass along the necessary values. You can do this either by passing variables : FunctionName ($Variable1, $Variable2, etc.); or by placing values within quotes, as in FunctionName ("Value1", "Value2", etc.); or some combination thereof: FunctionName ($Variable1, "Value2", etc.); The important thing to note is that arguments are passed quite literally in that the first value in the function will be equal to the first value in the call line, the second function value matches the second call value, and so forth. Functions are not smart enough to intuitively understand how you meant the values to be associated. This is also true if you fail to pass a value, in which case the function will assume that value is null ( null is not the mathematical 0, which is actually a value, but closer to the idea of the word nothing ). The same thing applies if a function takes four arguments and you pass threethe fourth will be null. To demonstrate functions that take arguments, you'll rewrite the hello.php page from Chapter 6, Control Structures . You'll place the greeting code into a simple function that takes an argumentthe user 's name . To create and call a function that takes an argument:
Tip In Chapter 13, Creating Web Applications , you'll see how to place certain information into external files which can be used in several pages. An external file will often be the best place to put your own functions, such as GreetUser, so they will be universally accessible throughout the entire Web site.
Tip Technically if you pass a number as an argument in a function, it does not need to be within strings but there is no harm in using strings anyway to remain consistent as to how arguments are passed. |
I l @ ve RuBoard |