Web Development

Writing user-defined functions in PHP

PHP lets you write your own functions, which saves you from rewriting code and helps keep your applications smaller. Here's a look at the basics of writing user-defined functions and some examples of how you can put them to work.

By definition, PHP is just a scripting language used on Web sites. However, the authors of PHP extended it into a full-blown programming language that can be used both for simple applications and for complex object-oriented programming tasks.

Among PHP's useful features are its many built-in functions, such as print() and mysql_query(), which meet a variety of needs. But PHP also allows you to write your own functions. The primary advantage of custom functions is reuse. If you don't write functions, you may have to write the same piece of code numerous times in your application, whether it's within the same PHP file or in others. Here's a look at how you can take advantage of user-defined functions in your own PHP code.

Anatomy of a function
Writing your own functions is as simple as using the function command like this:
function somefunction() {  [php code]   }

The command function is followed by the unique name of your function (in this case somefunction). Next comes the parentheses, which may contain variable names, and the actual function code itself, enclosed in curly braces.

Here's a basic example:
function helloworld() {   print("Hello world!<br>\n");  }

This function simply prints the text "Hello world!" to the Web page. It can be called just like a regular PHP function:
<html>
<body>
<?
  include("functions.inc.php");
  helloworld();
?>
</body>
</html>

In this example, we assume that the file Functions.inc.php contains our helloworld() function. After we include the file containing the function, we call the function itself.

Of course, functions can be more complex than this example. They can receive variables as input and can return data that can be assigned to another variable. For instance, this function creates a single row of data in a table, and the data is passed to the function:
function simpletable($text) {
  print("<table border=0 cellpadding=0 cellspacing=0><tr>");
  print("<td>$text</td>");
  print("</tr></table>");  }

In this case, we would use the function like this:
simpletable("This is my row of data");

Functions can receive multiple variables by using a comma delimiter to separate them. For example, we can extend simpletable() to allow the user to change the border, cellpadding, and cellspacing values:
function simpletable($text, $border="0", $cellp="0", $cells="0") {
  print("<table border=$border cellpadding=$cellp cellspacing=$cells><tr>");
  print("<td>$text</td>");
  print("</tr></table>");  }

The simpletable() function would then be called like this:
simpletable("This is my row of data", 0, 1, 1);

This assigns $border, $cellp, and $cells a default value of 0 so that if only one variable or field is passed to the function, we have default values for our border, cellpadding, and cellspacing values in the table. In the above call to simpletable(), we pass "This is my row of data" as the text to be displayed in the table, a border of 0, and a cellpadding and cellspacing value of 1.

Giving something back
You can use functions to return data as well as to receive it. Consider a simple function called multnum(), which multiplies two numbers. It must receive the two numbers as input; it will then return the multiplied result as output. You would write the function like this:
function multnum($n1, $n2) {
  $result = $n1 * $n2;
  return($result);  }

Here's how you might use multnum() in your code:
$total = multnum(5,10);

In this case, the value of $total will be 50. The function multiplies the two numbers received as input, assigns that value to $result, and with the return command makes the return value of the function equivalent to the value of $result.

It's important to be aware that functions are separate pieces of code, meaning that variables outside the function are not available inside the function. If you have a variable in your code that you want to use in your function, you will either have to pass it as input to your function or use the global command. The global command will make the specified variables available. Here's an example:
function somefunction($somevar) {  global $config, $othervar   ... }

We're making three variables available to the function somefunction(): $somevar, which is passed as input, and $config and $othervar, which are defined outside of the scope of the function but made available inside the function with the global command. Without the global command, the variable $config in this instance would return a NULL value because it was not defined inside the function itself.

For small applications, such as a one-page site, you can place the functions at the top of the file, before the rest of the code. For larger applications and multipage sites, it might be prudent to consider putting all your functions in a special file. You could then use the include() function to include this file in each of your Web pages, giving your functions a little more portability, reducing the size of your applications, and consolidating the global function in one file.

A good name for this file might be Functions.php or Functions.inc.php. Some PHP applications use filenames such as Functions.inc, which omit the .php extension, but this is a bad idea. You should keep the .php extension on the file to keep your code private. If visitors load the Functions.php file directly, they'll see nothing; however, if they load a file called Functions.inc, they'll see your source code, which could give out sensitive information such as path locations, passwords, and so forth.

As we've seen, the process of writing custom functions in PHP is straightforward. And taking advantage of user-defined functions makes a lot of sense, since they save you work, reduce the size of your apps, and facilitate code portability.

About

Vincent Danen works on the Red Hat Security Response Team and lives in Canada. He has been writing about and developing on Linux for over 10 years and is a veteran Mac user.

0 comments

Editor's Picks