PHP for the World Wide Web (Visual QuickStart Guide)
I l @ ve RuBoard |
As you program, you'll discover that there are certain sections of code you frequently use, either within a single script or in several. Placing these routines into a self-defined function can save you time and make your programming easier, especially as your Web sites become larger. Once you create a function, the actions of that function take place each time the function is called, just as print() will send text to the browser with each use. The syntax to create a user -defined function is: function FunctionName () { statement(s); } You can use roughly the same naming conventions for the function name as you do for variables , just without the initial dollar sign. The most important rule is to remain consistent. Second to that is the suggestion of creating meaningful function names, just as you ought to write representative variable names ( CreateHeader would be a better function name than Function1 ). Remember not to use spaces, though, as that would constitute two separate words for the function name, which will result in error messages (the underscore is a logical replacement for the space, for example Create_Header is a valid function name). Any valid PHP code can go within the statement(s) area of the function, including calls to other functions. There is also no limit to the number of statements a function has, but make sure each statement ends with a semi- colon . The formatting of a function is not important as long as the requisite elements are there. These elements include the word function , the function's name, the opening and closing parentheses, the opening and closing braces, and the statement(s).It is conventional to indent a function's statement(s) from the previous line (as I have done), for clarity's sake. In any case, select a format style that you like (which is both syntactically correct and logically sound) and stick to it. You call (or enact) the function by referring to it just as you do any built-in function. The line of code FunctionName(); will cause the statement(s); part of the predefined function above to be executed. Let's begin by rewriting the password- generating script from Chapter 5, Using Strings , as its own function. To create and call a basic function:
Tip If the server you are working on is running PHP 3, you must define the function before calling it. Although this is not true in PHP 4, I would recommend that you habitually set your functions at the beginning of a script, insuring they will always be created before being called.
Tip Function names for the functions you create are case-insensitive, just as existing PHP functions are case-insensitive. Therefore it won't matter in your code if you use createpassword instead of the more proper CreatePassword .
|
I l @ ve RuBoard |