Приглашаем посетить
Набоков (nabokov-lit.ru)

5.1 Declaring and Calling Functions

Previous Table of Contents Next

5.1 Declaring and Calling Functions

To create a new function, use the function keyword, followed by the function name and then, inside curly braces, the function body. Example 5-1 declares a new function called page_header( ).[1]

[1] Strictly speaking, the parentheses aren't part of the function name, but it's good practice to include them when referring to functions. Doing so helps you to distinguish functions from variables and other language constructs.

Example 5-1. Declaring a function
function page_header( ) {

    print '<html><head><title>Welcome to my site</title></head>';

    print '<body bgcolor="#ffffff">';

}

Function names follow the same rules as variable names: they must begin with a letter or an underscore, and the rest of the characters in the name can be letters, numbers, or underscores. The PHP interpreter doesn't prevent you from having a variable and a function with the same name, but you should avoid it if you can. Many things with similar names makes for programs that are hard to understand.

The page_header( ) function defined in Example 5-1 can be called just like a built-in function. Example 5-2 uses page_header( ) to print a complete page.

Example 5-2. Calling a function
page_header( );

print "Welcome, $user";

print "</body></html>";

Functions can be defined before or after they are called. The PHP interpreter reads the entire program file and takes care of all the function definitions before it runs any of the commands in the file. The page_header( ) and page_footer( ) functions in Example 5-3 both execute successfully, even though page_header( ) is defined before it is called and page_footer( ) is defined after it is called.

Example 5-3. Defining functions before or after calling them
function page_header( ) {

    print '<html><head><title>Welcome to my site</title></head>';

    print '<body bgcolor="#ffffff">';

}



page_header( );

print "Welcome, $user";

page_footer( );



function page_footer( ) {

    print '<hr>Thanks for visiting.';

    print '</body></html>';

}

    Previous Table of Contents Next