Groups of Logic: Declaring and Calling Functions in PHP

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().

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 engine 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 engine 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>’;

}

Source: Sklar David (2016), Learning PHP: A Gentle Introduction to the Web’s Most Popular Language, O’Reilly Media; 1st edition.

Leave a Reply

Your email address will not be published. Required fields are marked *