The Birth of a Function
Jason Lotito on 2001 March 13
    

I will be honest. I keep learning new things everyday. And as I learn new things, I wish I could go back and add on to the tutorials I have done, and go further into detail. But then I remember, I have so much more to teach. So rather than going back, I am going to move forward.

Functions are the backbone of programming. If you don't use functions, shame on you. They make your life as a hacker/programmer/code/guru/phphead so much easier. So, here I am to tell you how to create functions. =)



The Basics

A function in PHP is really easy to declare. To declare a function, you do this:


<?php
function blah()
{
     echo 
"blah blah blah";
}

?>


So, their is your function. The function name is blah. To use the blah function, you would call it like this:


<?php


blah
();


?>


See, pretty simple, huh? Okay, so lets start working with the function to make it more useful.

Functions can be used for so many different things, but be assured, they should be used in EVERY program you write. I don't know of any case where a function would NOT be useful. It helps to streamline development of a program. Rather than having to retype something over and over again, you type it once, and thats it.

So, lets create a useful function called dbconnect() and another function called query_db(). They will be written like this:


<?php
$dbhost 
'localhost';
$dbuname 'username';
$dbpage 'password';
$dbname 'database_name';

function 
dbconnect()
{
 global 
$dbhost$dbuname$dbpass$dbname;
 
mysql_pconnect($dbhost$dbuname$dbpass);
 @
mysql_select_db($dbname) or die ("Unable to select database");
}

function 
query_db($query)
{
 
dbconnect();
 return @
mysql_query($query);
}

?>


Now, don't worry about what they do yet. I will go over everything. Just be assured that what you are about to learn is basically how all program get written.

Lets take a look at the first function, dbconnect(). While dbconnect() is not a part of the PHP internal functions, like mysql_db_query(), echo() and include(), it is a very common function to use in a program. In fact, the majority of PHP programs that use databases create a function similair to this one. Now you will, too!

The first four lines are merely declarations. We are defining a few variables to be used later on.



Next, we define the function:


<?php
function dbconnect()

?>


So, the name of the function is dbconnect. Next, we are going to tell the function what to do. Whatever we want the function to do, we put in between the brackets, or the '{' and the '}'. This is what the function is going to do:


<?php
{
 global 
$dbhost$dbuname$dbpass$dbname;
 
mysql_pconnect($dbhost$dbuname$dbpass);
 @
mysql_select_db($dbname) or die ("Unable to select database");
}

?>


Now, taking a look at the first line, we see this:


<?php
global $dbhost$dbuname$dbpass$dbname;

?>


Wondering what that does? Well, let me tell you. Functions CAN'T use any outside variables (that is, outside what is defined in the function). The only variables a function can use is those defined either with the function name. This is commonly refered to as the 'Scope of the Variable', or the 'lifetime'. Basically, lets go off on a tangent here and take a long hard look at the scope of variables and how they affect functions.


<?php
$text 
"blah blah blah";

function 
blah()
{
     echo 
$text;
}

blah();

?>


Now, what would that display? Nothing, nothing would be outputted by the blah() function. But wait? Isn't the blah function supposed to be echo'ing the $text variable. And don't we define the $text variable at the top? Well, yes, while we do declare the $text variable, it isn't being used by the function. You see, imagine that the function is its own seperate operation. It will only use what it is given. In fact, if we did this:


<?php
$text 
"blah blah blah";

function 
blah()
{
     
$text "blah blah inside the function blah blah<br>";
     echo 
$text;
}

blah();
echo 
$text;

?>


You would get this:

blah blah inside the function blah blah
blah blah blah

That is because the $text inside the function has a scope, or a lifetime that only exists inside the function. As soon as it leaves the function, the function's $text no longer exists, and the normal $text is back at it again.

Understand? I hope so. But even if you are a little fuzzy on this (I was the first time I heard it), don't worry, we will be practicing with functions and scopes of variables next.


Back to dbconnect

Okay, now we move on to the good stuff. Back to dbconnect.


<?php
global $dbhost$dbuname$dbpass$dbname;

?>


This operator, global, actually allows use to use variables that are outside the function. You remember when we defined these? Well, rather than define them in the dbconnect function, we defined them outside the function. We did this in case we wanted to use the variables for another function. Because, remember, if we define a variable in a function, it is only alive for as long as the function itself is running.

So, global goes and gets the values of these functions

The next two lines:


<?php
 mysql_pconnect
($dbhost$dbuname$dbpass);
 @
mysql_select_db($dbname) or die ("Unable to select database");

?>


Are pretty self explanatory. They make a connection to the MySQL database. However, note that they are using the variables we defined above AND called in with 'global'. This makes it so the dbconnect function can be used over and over again for multiple programs. All you have to do as a programmer is copy the function into your program and set the variables. So, when you want to make a connection to the database, you simply type this into your program:


<?php
dbconnect
();

?>


Thats it. A lot nicer than having to type this out each time:


<?php
mysql_pconnect
($dbhost$dbuname$dbpass);
@
mysql_select_db($dbname) or die ("Unable to select database");

?>


Can you imagine the time saved?

Okay, so that was an easy one. Lets move on to the next function: query_db().


<?php
function query_db($query)
{
 
dbconnect();
 return @
mysql_query($query);
}

?>


No, here is what query_db does: It queries the database and returns the results to the program. How is this done? Lets go over this function.


<?php
function query_db($query

?>




Now, first things first, we declared and name the function. But this time, something is different. In between the ( and the ), I have a variable name? Yup, I sure do. And this is the reason why.

Everytime I call query_db as a function, I want to use a variable that contains a value which is needed. In order for me to query the database, I need to send along a query. So, whenever I call query_db, it will look like this:


<?php
$ename 
"JOSH";
$results query_db("SELECT * FROM emp WHERE ename='$name'");

?>


I could also do this:


<?php
$ename 
"JOSH";
$query "SELECT * FROM emp WHERE ename='$ename'";
$results query_db($query);

?>


I should quickly point out that the query variable above can be named anything. When we defined the function originally and used the $query variable in defining the function, that was simply the variable name we would use in the function itself. So, in the above example, we could instead do this:


<?php
$ename 
"JOSH";
$cheese "SELECT * FROM emp WHERE ename='$ename'";
$results query_db($cheese);

?>


And it would still be fine. However, doing this:


<?php
$results 
query_db();

?>


... would not work. Also, do not question why I have the '$results = ' part in there yet. I will explain it in a second. All in due time.

Okay, so, when we add a variable when defining a function, we can use that variable in the function In fact, we have to use it. The only way we don't have to use a variable like that is if we did this:


<?php
function query_db($query "SELECT * FROM bonehead")

?>


The ' = "SELECT * FROM bonehead' part basically says this: This function needs $query to be set to use the function, but if the user doesn't set the value of $query when calling the query_db function, than I will use the default value of 'SELECT * FROM bonehead'. Basically, it sets the default value. I just want to also point out that if you are going to use default values, and you use more than one variable, you have to put the variables with the default settings at the end of the function, like this:


<?php
function query_db($name$phonenumber$query "SELECT * FROM bonehead")

?>


Its also good to point out that yes, you can have more than one variable passed into a function. Just seperate them with a comma.



Whew, man, that was just long to write, but I am sure its even longer to read. Hopefully you are still hanging in there with me. If you haven't yet, take a break, grab a Coke or Mountain Dew, and stretch. Lord knows I am going to take one. =)

Okay, back from my break (watched a few minutes of the Simpsons, grabbed a Dew, laughed at my roomie), lets get back to work.


<?php
dbconnect
();
 return @
mysql_query($query);

?>


Okay, so that is what our query_db() function is doing. First, its calling the first function we made, dbconnect(). So, it connects us to the database. The next thing it does is performs a query using mysql_query function. Do you see the variable $query being used? That takes the query we set in query_db($query) when we called the function, and uses it for the mysql_query() function.

Wait, what about the return? What the heck is that for? Well, remember when I was talking about the life of a variable? Well, the only way for us to send a value back out of the function back to the program is to return it.

So, what we are doing is returning the value of the mysql_query() function. The value of that is sent to another variable, which in our case, is results. Remember this:


<?php
$results 
query_db($cheese); 

?>


This calls the query_db() function, and take whatever is returned via return in the function and puts it into the variable $results. Its the same as doing this:


<?php
dbconnect
();
 
$results = @mysql_query($query);

?>


Now, why wouldn't I do that instead? Because, I don't want to type in dbconnect(); each and everytime. Lazy, aint I? But just imagne this. Using those two functions, I can now type this:


<?php
$name 
"BOB";
$results query_db("SELECT name FROM emp WHERE name='$name'");

?>


Instead of having to type all this out:


<?php
mysql_pconnect
($dbhost$dbuname$dbpass);
@
mysql_select_db($dbname) or die ("Unable to select database");
$name "BOB";
$results query_db("SELECT name FROM emp WHERE name='$name'");
$results = @mysql_query($query);

?>


Now, figure this. Lets say in your program you are going to be doing a total of 10 queries (and mind you, that is a small number of queries). Which would you rather type out each time. Which is easier to read? What about maintain? Accidentally code something wrong, and then you copy and paste it into a dozen places. Heck, that is bad news for you. However, with functions, you simply fix the function, and all 10 queries are working. It is also easier when making new programs. Think about it. You can create a db_connection.php page where you keep these functions at. Simply include them into any script you are working on, and they work.

Much easier, huh?
Tentatively planning to Open Soon! (no dates ...) // Doing heavy development now...