PHP
By Web Monkey
Page 4 Functions
--------------------------------------------------------------------------------
Enjoy that last regex expression? Fun, wasn't it? Wouldn't
it be even more fun to enter that chunk on a dozen different
pages that need to process email addresses?! Think about the
joy of finding a typo in that mess - and doing it a dozen
times no less. But of course, there's a better way.
Remember when we talked about include files earlier in this
lesson? They'll allow us to create a piece of code like the
email checker and include it multiple times across several
pages. This way, when we want to change the code, we need
edit only one file, not many.
But if we want to get this done, we'll have to use functions.
We've already used functions plenty of times. Every time
we query the database or check the length of a string we're
using functions. These functions are built into PHP. If you're
a keen coder, you can extend PHP with your own customized
functions. But that's a bit advanced for this tutorial. Instead
we'll create functions that will reside within our PHP script.
A function is simply a block of code that we pass one or
more values to. The function then processes the information
and returns a value. The function can be as simple or complex
as we like, but as long as we can pass a value in and get
one out, we don't really care how complex it is. That's the
beauty of functions.
Functions in PHP behave similarly to functions in C. When
we define the functions, we must specify what values the function
can expect to receive. It's tricky to get a handle on at first,
but it prevents weird things from happening down the road.
This is done because the variables inside a function are known
as private variables. That is, they exist only inside the
function. You may, for instance, have a variable in your script
called $myname. If you created a function and expected to
use the same $myname variable (with the same value), it wouldn't
work. Alternatively, you could have the variable $myname in
your script and also create another variable called $myname
in your function, and the two would co-exist quite happily
with separate values. I do not recommend doing this, however!
When you come back and edit it six months later, you'll be
breaking things left and right. There are exceptions to this
rule as with all things, but that's outside the scope of this
article.
So let's create a function. We'll start simply. We need to
give the function a name and tell it what variables to expect.
We also need to define the function before we call it.
<html>
<body>
<?php
function
addnum($first, $second) {
$newnum
= $first + $second;
return
$newnum;
}
echo
addnum(4,5);
?>
</body>
</html>
That's it! First, we created our function. Notice how we defined
two new variables, called $first and $second. When we call
the function, each variable is assigned a value based on the
order in which it appears in the list - 4 goes to $first,
5 to $second. Then we simply added the two numbers together
and returned the result. "Return" here simply means
to send the result back. At the end of the script we print
the number 9.
Let's create something that's more useful to our database
application. How about something that gracefully handles errors?
Try this:
<html>
<body>
<?php
function
do_error($error) {
echo
"Hmm, looks like there was a problem here...<br>";
echo
"The reported error was $error.\n<br>";
echo
"Best you get hold of the site admin and let her know.";
die;
}
if
(!$db = @mysql_connect("localhost","user",
"password")) {
$db_error
= "Could not connect to MySQL Server";
do_error($db_error);
}
?>
</body>
</html>
Before running this, try shutting down MySQL or using a bogus
username or password. You'll get a nice, useful error message.
Observant readers will notice the @ symbol in front of mysql_connect().
This suppresses error messages so that you get the information
only from the function. You'll also see we were able to pass
a variable into the function, which was defined elsewhere.
Remember that I said functions use their own private variables?
That was a little white lie. In fact, you can make variables
outside of a function accessible to the function. You might
create a function to query a database and display a set of
results over several pages. You don't want to have to pass
the database connection identifier into the function every
time. So in this situation, you can make connection code available
as a global variable. For example:
<html>
<body>
<?php
function
db_query($sql) {
global
$db;
$result
= mysql_query($sql,$db);
return
$result;
}
$sql
= "SELECT * FROM mytable";
$result
= db_query($sql);
?>
</body>
</html>
This is a basic function, but the point is that you don't
need to send $db through when you call the function - you
can make it available using the word global. You can define
other variables as global in this statement, just separate
the variable names by a comma.
Finally, you can look like a real pro by using optional function
variables. Here, the key is to define the variable to some
default in the function, then when you call the function without
specifying a value for the variable, the default will be adopted.
But if you do specify a value, it will take precedence.
Confused? For example, when you connect to a database, you
nearly always connect to the same server and you'll likely
use the same username and password. But sometimes you'll need
to connect to a different database. Let's take a look.
<html>
<body>
<?php
function
db_connect($host = "localhost", $user="username",
$pass="graeme") {
$db
= mysql_connect($host, $username, $password);
return
$db;
}
$old_db
= db_connect();
$new_host
= "site.com";
$new_db
= db_connect($new_host);
?>
</body>
</html>
Isn't that cool? The variables used inside the function were
defined when the function was defined. The first time the
function is called, the defaults are used. The second time,
we connect to a new host, but with the same username and password.
Great stuff!
Think about where you could use other functions in your code.
You could use them for data checking, performing routine tasks,
and so on. I use them a lot when processing text for display
on a Web page. I can check, parse, and modify the text to
add new lines and escape HTML characters in one fell swoop.
Now all that's left to do is to impart some words of wisdom.
next page»
|