Section 5.2. Defining Functions


5.2. Defining Functions

There are already many functions built into PHP. However, you can define your own and organize your code into functions. To define your own functions, start out with the function statement:

 function some_function([arguments]) { code to execute } 

The brackets ([ ]) mean optional. The code could also be written with optional_arguments in place of [arguments]. The function keyword is followed by the name of the function. Function names abide by the same rules as other named objects such as variables in PHP. A pair of parentheses must come next. If your function has parameters, they're specified within the parentheses. Finally, the code to execute is listed between curly brackets, as seen in the code above.

You can define functions anywhere in your code and call them from virtually anywhere. Scope rules apply. The scope of a variable is the context within which it's defined. For the most part, all PHP variables have only a single scope. A single scope spans included and required files as well. The function is defined on the same page or included in an include file. Functions can have parameters and return values that allow you to reuse code.

To create your own function that simply displays a different hello message, you would write:

 <?php function hi() {   echo ("Hello from function-land!"); } //Call the function hi(); ?> 

which displays:

 Hello from function-land! 

The hi function doesn't take any parameters, so you don't list anything between the parentheses. Now that you've defined a simple function, let's mix in some parameters.

5.2.1. Parameters

Parameters provide a convenient way to pass information to a function when you call it without having to worry about variable scope. In PHP, you don't have to define what type of data a parameter holdsonly the name and number of parameters must be specified.

An example of a function is strtolower, which converts your string "Hello world!" to lowercase. It takes a parameter of the type string, which is a data type (described in a previous chapter). There's also another function strtoupper that converts all characters of your string into uppercase letters, as shown in Example 5-4.

Example 5-4. Using the string capitalization functions

 <?php // Capitalize a string function capitalize( $str ) {   // First, convert all characters to lower case   $str = strtolower($str);   // Second, convert the first character to upper case   $str{0} = strtoupper($str{0});   echo $str; } capitalize("hEllo WoRld!" ); ?> 

Example 5-4 outputs:

 Hello world! 

The value of $str was echoed inside the function, because you didn't specify any way to get the value out of the function.

PHP also doesn't require definition of whether a function actually returns a value, or what data type it returns.


Parameters can also contain default values. With a default value, you actually don't need to pass the function any input for it to set the default. Let's change your capitalize function to have a default value that allows you to capitalize the first letter of each word or just the sentence; see Example 5-5.

Example 5-5. Creating a capitalize function with a default parameter $each

 <?php // Capitalize a string or the first letter of each word function capitalize( $str, $each=TRUE ) {   // First, convert all characters to lower case   $str = strtolower($str);   if ($each === TRUE) {      $str = ucwords ($str);   } else {      $str = strtoupper($str);   }   echo ("$str <br>"); } capitalize("hEllo WoRld!"); echo ("Now do the same with the echo parameter set to FALSE.<br>"); capitalize("hEllo WoRld!",FALSE); ?> 

Example 5-5 produces:

 Hello World! Now do the same with the echo parameter set to FALSE. HELLO WORLD! 

Example 5-5 shows that when you execute capitalize with just one parameter, hEllo WoRld!, $each takes on the default value of TRUE. Therefore, only the first letter of each word gets capitalized. When the second execution of capitalize sends in a value of FALSE from the parameter, $each becomes FALSE in the function and the output changes. Also, ucwords changes the first character of a string to uppercase.

5.2.2. Parameter References

When you pass an argument to the function, a local copy is made in the function to store the value. Any changes made to that value don't affect the source of the parameter. You can define parameters that modify the source variable by defining reference parameters.

Reference parameters define references by placing an ampersand (&) directly before the parameter in the functions definition.

Let's modify the capitalize function from Example 5-5 to take a reference variable for the string to capitalize (Example 5-6).

Example 5-6. Modifying capitalize to take a reference parameter

 <?php function capitalize( &$str, $each=true ) {     // First, convert all characters to lower case     $str = strtolower($str);    if ($each === true) {       $str = ucwords($str);    } else {       $str{0} = strtoupper($str{0});    } } $str = "hEllo WoRld!"; capitalize( &$str ); echo $str; ?> 

Example 5-6 returns:

 Hello World! 

Because capitalize defined the $str parameter as a reference parameter, a link to the source variable was sent to the function when it was executed. The function essentially accessed and modified the source variable. Had the variable not been declared as a reference, the original value of "hEllo WoRld!" would display.

5.2.3. Including and Requiring PHP Files

To make your code more readable, you can place your functions in a separate file. Many PHP add-ons that you download off the Internet contain functions already placed into files that you simply include in your PHP program. However, PHP provides four functions that enable you to insert code from other files.

  • include

  • require

  • include_once

  • require_once

All the include and require functions can take a local file or URL as input, but they cannot import a remote file. require and include functions are pretty similar in their functionality except for the way in which they handle an irretrievable resource. For example, include and include_once provide a warning if the resource cannot be retrieved and try to continue execution of the program. The require and require_once functions provide stop processing of the particular page if they can't retrieve the resource. Now we're going to get more specific about these four functions.

5.2.4. The include Statement

The include statement allows you to include and attach other PHP scripts to your own script. You can think of it as simply taking the included file and inserting them into your PHP file. Example 5-7 is called add.php.

Example 5-7. A sample include file called add.php

 <?php function add( $x, $y ) {   return $x + $y; } ?> 

Example 5-8 assumes that add.php is in the same directory as the include function.

Example 5-8. Using the include function

 <?php include('add.php'); echo add(2, 2); ?> 

When executed, this produces:

 4 

As seen in Example 5-8, the include statement attaches other PHP scripts so that you can access other variables, functions, and classes.

You can name your include files anything that you like, but you should always use the .php extension, because if you name them something else, such as .inc, it's possible that a user can request the .inc file and that the web server will return the code stored in it. This is a security risk, as it may reveal passwords or details about how your program works that can reveal weaknesses in your code. This is because PHP files are parsed by the PHP interpreter.


5.2.4.1. The include_once statement

A problem may arise when you include many nested PHP scripts, because the include statement doesn't check for scripts that have already been included.

For example, if you did this:

 <?php include('add.php'); include('add.php'); echo add(2, 2); ?> 

You'd get this error:

 Fatal error: Cannot redeclare add() (previously declared in /home/www/htmlkb/oreilly/ch5/add.php:2) in /home/www/htmlkb/oreilly/ch5/add.php on line 2 

The above directory may not be where your file is located; your file will go wherever you've designated a place for it. To avoid this type of error, you should use the include_once statement.

Example 5-9 shows the include_once statement.

Example 5-9. Using include_once to include a file

 <?php include_once('add.php'); include_once('add.php'); echo add(2, 2); ?> 

This outputs the following when executed:

 4 

Obviously, you're not going to place the same include statements right next to each other, but it's far more likely that you may include a file, which includes another file you've already included. You should always use include_once, as there really isn't any drawback to using it instead of include.

There are a couple of problems to look out for when using include or include_once that can prevent the code from being included. If the file has been deleted, obviously, PHP can't include it. The other problem is if the include statement is accidentally deleted from the PHP page. This can happen if the include statement isn't obviously related to the code that uses it and nearby the code in the file. One way to prevent this problem is to place the code that uses the included code in a function that's defined next to the include statement. Then place a call to the function where you need to use the code in your main PHP code. Additionally, you could use include_once at the beginning of the function definition, making it very clear that the code needs the included file.

As demonstrated in the above two paragraphs, there are many potential solutions to numerous problems you may run into while creating functions and scripts. Keep in mind that coding is an iterative process, and, as we'll discuss in Chapter 15, you can use all the resources available on the Internet from other PHP programmers to help you work through any code issues and problems you may have while coding. The PHP community is available to help with all issues, and usually gets back to a posting board quicker than it might take you to sort out your problem!

5.2.4.2. require and require_once functions

To make sure that a file is included and to stop your program, immediately use require and its counter part, require_once. These are exactly the same as include and include_once except that they make sure that the file is present; otherwise, the PHP script's execution is halted, which wouldn't be a good thing! Examples of when you should use require instead of include are if the file you're including defines critical functions that your script won't be able to execute or variable definitions such as database connection details.

For example, if you attempt to require a file that doesn't exist:

 <?php require_once('add_wrong.php'); echo add(2, 2); ?> 

you'd get this error:

 Warning: main(add_wrong.php): failed to open stream: No such file or directory in /home/www/htmlkb/oreilly/ch5/require_once.php on line 2 Fatal error: main(): Failed opening required 'add_wrong.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/www/htmlkb/oreilly/ch5/require_once.php on line 2 

All file paths are contingent on where your files are located. The last topic we'll cover with functions is how to test whether a function has been defined before attempting to use it.

5.2.5. Testing a Function

If compatibility with various PHP versions is especially important to your script, it's useful to be able to check for the existence of functions. The function function_exists does just what you'd expect. It takes a string with a function's name and returns trUE or FALSE depending on whether the function has been defined. For example:

 <?php $test=function_exists("test_this"); if ($test==TRUE) { echo "Function test_this exists."; } else {   echo "Function test_this does not exist."; //call_different_function(); } ?> 

displays:

 Function test_this does not exist. 

The "Function test_this does not exist" message displays because you haven't defined the function test_this, therefore the program code either displays an error message in plain English or attempts to use a different function.

You've learned how to define functions and their parameters, and how to pass information back and forth from them, plus we've given you some good examples of how to troubleshoot potential function problems.

Next, we'll introduce an alternate style of programming called Object-Orientated (OO) programming. PHP 4.1 had minimal support for OO programming, but with the introduction of 5.0, OO is fully developed. There is continuous debate about which type of coding is better, and really, neither is better or worse than the other; it's mostly a style issue and personal preference.



Learning PHP and MySQL
Learning PHP and MySQL
ISBN: 0596101104
EAN: 2147483647
Year: N/A
Pages: 135

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net