Languages PHP Functions in PHP

Functions in PHP

A complete PHP application
might contain upwards of dozens of individual script files, with hundreds
of lines of code in each. Between all of those, there will be many instances
where the same piece of code is reused: something as simple as outputting
a string to the browser or as complex as making sure a user is logged
in across multiple pages, and prompting them for login information if
they are not.

As you might imagine, copying the same code you need to every location
you need it in is neither practical nor efficient.

Fortunately PHP, like most other programming languages, includes a language
structure called a Function. A Function is a self-contained code block
that performs a specific job. In most cases, they accept input from the
main script as arguments, and return some kind of result. They can help
modularize a script by allowing the programmer to break the script down
by task. They are also portable, so if you write a useful function for
one script, you can easily reuse it in another.

In this article, we will be covering some introductory information on
functions. We will also be taking a brief look at PHP’s pre-defined functions
before focusing on creating and using your own.


Pre-Defined Functions

One of things that makes PHP
so easy to use is the wealth of built in functions. These functions provide
the tools to easily complete many of the everyday tasks you need to perform
in the course of writing a full-fledged application. There are functions
for working with just about everything in PHP: strings, arrays, databases,
dates and times, email, numbers, even functions for working with other
functions.

With so many out there, it would be impossible to cover all of PHP’s functions
in a single article. However, as the series progresses, you will be introduced
to many of the more useful ones. You can also find the complete list of
PHP’s built in functions at the their
site
.

Right now, let’s take a look at a couple of these functions, just to explore
how they can be used.

print()

Though you have probably used it before without thinking about it, print();
is actually a built in PHP function. Basically, print accepts a string
as an argument and outputs it. It’s a little unique because it works with
or without parentheses:

<?php
print “This is a test<br>n”;
print (“This is a test<br>n”);
?>



include()

include(), which allows you to include one file inside of another, is
one of those functions that you will find yourself using all the time. If
you have ever seen web sites using php where the links to other pages within
the site look like http://www.domain.com/?page=pagename or http://www.domain.com/?pagename,
it is likely that they are using this function to dynamically generate their
web pages from included files.

To see how it works, first create a file called test.txt and write some
text in it. Next, create a new PHP file called test.php and place the following
inside of it. Just like print(), the parentheses are optional:

<?php
include “text.txt”;
?>

Make sure both are saved to the same directory on your web server. When
you run test.php, you will see that the text you placed in text.txt was
outputted to the browser.

You can easily include text, html or php files in this manner.

header()

This function allows
you to send a raw HTTP header. Most of its applications are technical, but
one of the most common uses is something relatively simple: redirecting
the user. This has the same effect as the META redirection tag in HTML:

<?php
header(
“Location:http://webdeveloper.earthweb.com/”);
exit;
?>


Keep in mind that if you use header(), it must be called before outputting
any information to the browser, either from PHP or HTML.

User-Defined
Functions

As invaluable
as PHP’s built in functions are, the real power and flexibility comes
from being able to write and utilize your own. Imagine you wanted to do
something very simple, like print out a greeting. There is no real reason
why you would actually need to use a function for something like this,
but for the purposes of the next few examples we will. Take a look at
the following:

<?php
function say_hi() {
print “Hi there!”;
}
?>


At this point, nothing is outputted to the browser because we are only
defining what the function is called, and what it will do.

Let’s take a closer
look at what exactly this code means.

The first line begins
with the word “function”, which tells PHP that we are starting to write
a function. “Say_hi” is the name of the function. Just like variable names,
function names must be one word, and can only contain letters, numbers,
and underscores. They cannot begin with a number and are case sensitive.
The name is followed by an opening and closing set of parentheses, which
can house optional arguments, and an opening bracket that denotes where
the code within the function begins.

Unlike Control Structures,
the opening and closing brackets on functions are required even if you
only have one line of code between them.

To actually execute this function, it needs to be called, just like PHP’s
predefined functions:

<?php
function say_hi() {
print “Hi there!”;
}

say_hi();
?>

Keep in mind that since version
4 of PHP, it has not been necessary to declare a function before calling
it.


Returning Values from a Function

In the last snippet,
text was ouputted directly from inside the function using print(), but
what if you just wanted to return a value without actually outputting
it? Let’s take a look at our example again:

<?php
function say_hi() {
return “Hi there!”;
}

$var = say_hi();
print $var;
print say_hi();
?>


Notice how the line within the function has changed: “Hi there” is now
preceded by the return statement. When you call a function that uses the
return statement, rather than executing and immediately outputting whatever
was in the function, the value following "return" is treated
as the result of the function. This resulting value can be a string, integer,
variable or any other PHP data type. When the function is called, the
result can be assigned to a variable, or printed out.

PHP technically only
allows you to return a single value, but there are ways around this limitation
through the use of Arrays, as you will later learn.

Function Arguments

Imagine that we
wanted to make our little script a little more personalized, and greet
someone by their name. To do this, we want to make the function accept
an argument:

<?php
function say_hi($name) {
return “Hi there $name!”;
}
?>

In the function definition,
we give the argument a variable name. This is the name that the argument
will be accessible as within the function. Calling the function is the
same as before, except this time we include a string between the parentheses
as an argument:

<?php
print say_hi(“Billy Joe Bob”);
?>


PHP allows you to have as many arguments as you wish. To include more
than one, you need to separate them with a comma:

<?php
function
say_hi($name, $greeting) {
   return “$greeting $name!”;
}

print say_hi(“Billy Joe Bob”, “Hi there”);
?>

In most cases (although not all),
you must have a matching number of arguments in the function defination
and in the function call.


Variable Scope

If you are migrating
to PHP from another programming language, you probably are already familiar
with the concept of variable scope; however PHP handles it slightly different
from other languages.

For those of you unfamiliar with the concept: Scope determines where within
a script a variable can be used. In PHP, variables have a single, global
scope by default, meaning that they are available for use within the main
script and any included or required files, but not within functions.
By the same token, a variable created or altered within the function would
not automatically be available to the entire script, because it was created
within the local scope of the function.

Obviously, you need to be able to move variables from the scope of the
main script to the scope of the function in order to work with them. You
also be able to take those variables back into the scope of the main script.
To do this, we pass variables to, and return them from, the function.

Since we have already taken a brief look at returning variables, let’s
look at several of the more common ways to move a variable from the global
scope of the script to the local scope of a function.

1. Pass the variable
as an argument to the function
This is the easiest
and most common method. To illustrate, let’s look at our simple greeting
script again. Rather than passing the name directly to the script as an
argument, it will be defined as a variable first:

<?php
$name = “Billy Joe Bob”;

function say_hi($name) {
    return “Hi there $name!”;
}

print say_hi($name);
?>


It is important to keep in mind that when you pass a variable like this,
you are actually copying the value of the original variable to a new variable
within the local scope of the function. This means that even if you use
the same name, changes to the variable within the function will not affect
the variable outside the function. Take a look at this example to see
this rule in action:

<?php
$x = 1;

function add($x) {
$y++;
print $y;
}

add($x);
print $x;
?>

2. Pass the variable as
a reference
References alone are an expansive topic to cover, so we will just
take a quick look at how they can be used with functions. This method
is very similar to the first; however instead of copying the value of
a variable to a new one within a function, you are pointing the new variable
name to the same value.

Technically, two different variable names, one within the global scope
of the script, and the other within the local scope of the function will
both point to the same value. If this seems confusing, try the following
sample and compare the results of this script to the previous one. Notice
the “&” before the variable name in the function definition, which
marks it as a reference:

<?php
$x
= 1;

function add(&$y) {
$y++;
}

add($x);
print $x;
?>


Since we are altering the actual value of $x from within the function,
there is no need to even return anything from the function. When $x is
printed out, its value will have increased by one.

3. Declare the variable
global within the function or access it via the GLOBALS array
Declaring a variable
as global has much the same effect as using a reference, but the reasoning
behind it is a little different. Rather than creating a new variable name
that references the same value as another, we are telling the script to
use the exact same variable and value inside the function. You can make
more than one variable global just by separating them by commas.

<?php
$x = 1;

function add() {
   global $x;
   $x++;
}

add();
print $x;
?>

You can also access variables
from the global scope of the script by using PHP’s GLOBALS Array. This
is an Associative Array which allows you to access each variable in the
form of $GLOBALS[”varname”]:

<?php
$x = 1;

function add() {
   $GLOBALS[”x”]++;
}

add();
print $x;
?>


Finally

By now, you should have a taste of the basics of functions: what they
are, how to use them, and how to create your own. You should also have
a basic understanding of Variable Scope and how it comes into play when
writing functions.

In the next article,
we will use functions extensively to manipulate Arrays and explore how
they work.

Stay Tuned!

Things to
Remember:

  • A Function is a self-contained
    code block that performs a specific job.
  • Functions accept
    arguments, which allow data to be passed to the function. Multiple
    arguments are seperated by commas.
  • The Scope of a variable
    determines where it can be used. By default, variables created
    in the main script are not available to functions within the script.
    They are, however, available to included and required files.
  • Variables can be
    passed from the global scope of the script to the local scope
    of the function in one of four ways: as arguments, as references,
    by declaring them as "global" within the function, or
    by using the GLOBALS array.
  • Variables created
    within a function, or passed as arguments can only be returned
    to the global scope of the script by using the return; statement.


Liz Fulghum currently lives in Annapolis, MD where she works as a web designer for a custom shirt retailer. Liz was convinced to try PHP as an alternative to Perl; she has been a fan ever since and frequently works as a freelance developer.

# # #

Latest Posts

Related Stories