Be a Supporter!

PHP: defining functions and stuff

  • 1,484 Views
  • 8 Replies
New Topic Respond to this Topic
Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
PHP: defining functions and stuff Jul. 23rd, 2006 @ 01:43 AM Reply

PHP Main

In this tutorial I will teach you how to define your own functions. You will see basic functions to complete common tasks or simple examples which are purely useless but show you key concepts in defining your own functions.

I'm sure you've all worked with functions, such as str_replace(), substr(), mysql_connect(), isset(), etc. They're all functions. There are, of course, differences in the functions themselves. From the naming styles, to the returned value types, to the overall purpose.

I'll be explaining how to decide which value types the function should return and how we decide whether to use a return value at all. I'll also be talking slightly in-depth about the features of code blocks and what should be kept in mind while dealing with them.

When you define a function, one keyword is needed to let the PHP engine know what you're trying to do. The keyword we're looking for is the function keyword. A basic function definition is done like so:

function functionName( argument list ) {
// some code
}

If you recall, most functions require what we call arguments, or values passed to the function to be modified, checked, verified, or other common tasks. However, some functions don't require any arguments, such as the phpinfo() function or the get_magic_quotes_*() functions. The same thing applies to user defined functions, they may or may not require arguments just as they may or may not return a value.

Let's go ahead and define a simple function. This function will simply add two values passed to it. While it's a basically worthless function, it shows how they're defined, etc.

function add($num1, $num2) {
return $num1+$num2;
}

Before you freak out over the return construct, let me explain the other parts of the code. This function's name is add and it accepts two arguments, which are both (supposed to be) numbers of some sort.

Remember how we use functions such as str_replace()? Let's say we pass a string to str_replace() like so and modify it.

$newStr = str_replace('shit', '%#^!', 'This is some horse shit');

Our new string would read: "This is some horse %#^!" and would be more reader friendly because we've censored out a curse word. Well, the returned value of this function is what is stored in the $newStr variable, or the string "This is some horse %#^!". Another way to think of a return value is the value that the function produces after performing the selected operations. Simple enough, right?

Let's show how we would call this function in our code.

echo 'The value of 2 plus 2 is ' . add(2, 2);

This would output "The value of 2 plus 2 is 4". Now, lets say you forgot to specify the second argument (or both arguments for that matter) while you were calling the function. You would get an error message similar to this one:

Warning: Missing argument 2 for add(), called in [remote path to file] on line [line of error] and defined in [remote path to file]

While this is not a fatal error and can be turned off with simple error handling functions (or in php.ini settings), it shouldn't be ignored. But what if we want a function to contain optional arguments like many functions, such as file(), fopen(), etc, do? Well, we can make arguments optional by specifying a default value in the parameter list while defining the function.

Let's modify the add() function we've already defined. Say we want it to require 2 numbers and be able to accept a 3rd number to add to the value. We could do so like this:

function add($num1, $num2, $num3 = 0) {
return $num1 + $num2 + $num3;
}

Now if we call this function like so:

add(2, 2, 5);

It would return the value 9, since 2 + 2 + 5 = 9. But let's say we only want to use two arguments and do it like this:

add(4, 20);

This would return 24 and WOULD NOT trigger the error shown above, because the third parameter of the function is optional! Now, sometimes optional parameters are used for brievity while coding. Let's say we create an incrementing function. Well, by default (and in most cases) we only want to increment our numbers by 1, so that would be assigned to the default value of the incrementing variable. Let's look at some code:

function inc($num, $val=1) {
return $num + $val;
}

Now, in most cases we could call the function like this:

inc(2); // Returns 3

But we could also do it like this:

inc(2, 6); // Returns 8

So now we have a concept down of defining functions, defining an argument list and using optional arguments with default values. Before I go on with this tutorial, I'm sure there are some of you out there scratching your heads about the terms "argument" and "parameter". Well, there is no real difference between these terms. They both describe the values passed to a function. But "argument" is usually the term chosen for discussing values passed to the function outside of the function. Likewise, "parameter" is used when you're talking about them inside of the function code block. That may sound confusing so let me draw you an example:


// Create the add() function with two required arguments and 1 optional argument
function add($num1, $num2, $num3=0) {
// $num3 is the optional parameter and $num1 and $num2 are required parameters
}

The difference is so minute they are almost (and usually) used interchangeably. Now that we've declared functions that return values, let's write some that don't return values but still acheive a purpose, even if it's useless.

Let's create a function which recreates the echo construct.

function outputContent($content) {
echo $content;
}

Now, if we call the function like this:

$returnedValue = outputContent('hello world!');

This will output "hello world!" on the user's screen; however, if we try echoing the value of $returnedValue which stores the returned value of the function (or lack of one, rather), then it won't output anything. Why you ask? It's because the function doesn't actually return anything at all. In fact, the value of $returnedValue is simply NULL, meaning no value at all.

Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
Response to PHP: defining functions and stuff Jul. 23rd, 2006 @ 01:44 AM Reply

Now that all that jibber jabber is done with, let's look at some functions which take no arguments but still return/output a value. Remember when I mentioned the functions such as get_magic_quotes_gpc() which don't require any arguments but still return a value? Let's write one ourself. This function will return the value of the user's IP address browsing the site.

function getIP() {
return $_SERVER['REMOTE_ADDR'];
}

We could call the function like so:

$userIP = getIP();

See how we don't specify any value for the function to work with? That's because the function doesn't really need a value to manipulate or work with in order to produce the desired result. In a similar way, we could create a function to output a commonly used string. We could create a function to let the user know what his/her IP address is. Observe the following code:

function showIP() {
echo 'You are browsing from the following IP address: ' . $_SERVER['REMOTE_ADDR'];
}

If you already had the getIP() function defined in your file, you could write the showIP() function like so:

function showIP() {
echo 'You are browsing from the following IP address: ' . getIP();
}

Once again, we don't pass any existing values to the function and it still produces the desired effect. Neat, huh?

Now, let's delve a little deeper in this whole function thing. Let's say we want to define a function such as the isset() function which doesn't have a set number of required OR optional arguments. How would we do this? Well, let's say you want to pass 100 items to the isset() function to determine if they exist. It wouldn't be practical for the function's author to create 100 optional arguments in the argument list. We can determine how many arguments the user is passing to the function and retrieve them with the func_num_args() and func_get_args() functions. Let's expand on our add() function to make it even more comprehensive!

function add() {
$totalArgs = func_num_args();
$args = func_get_args();

$total = 0;

for($curArg = 0; $curArg < $totalArgs; $curArg++) {
$total += $args[$curArg];
}

return $total;

}

Now, we could use as many arguments as we want and add them all together. Look at the following code:

add(3, 7, 10, 50, 100, 40, 30, 40, 10, 50); // Returns 340 (I think lol)

Let me explain the func_get_args() and func_num_args() functions. The func_get_args() function retrieves the actual values of the arguments being passed to the function. The func_num_args() counts the parameters being passed to the function. Keep in mind that func_num_args() DOES NOT use a zero-indexed counting system like arrays do. All this means is that in the case of a for loop we start the seed at 0 and specify the seed as less than (<) the total number of arguments.

Now, if we write this code below, no error is produced:

add();

Well, we want it to require at least 2 arguments, right? We can do that by slightly modifying the code above into the following:


function add($num1, $num2) {
$totalArgs = func_num_args();
$args = func_get_args();

$total = $num1 + $num2;

for($curArg = 2; $curArg < $totalArgs; $curArg++) {
$total += $args[$curArg];
}

return $total;

}

As you can see, 2 arguments have been added to the argument list. Since they have no default value they are considered required. We also made 2 more modifications. Instead of starting the $total variable at 0, we started it at the value of $num1 plus $num2, since we know for a fact (or hopefully) we're going to be given at least 2 numbers to add. We also start the $curArg (current argument) seed at 2 rather than 0 because we want to start on the key 2 (or 3rd element) of the $args array.

Lastly, I will discuss how to use global variables inside of local code blocks (in this case, functions). Let's say we have the following code:

$string = 'hey guys';
function echoString() {
echo $string;
}

Calling the function echoString(); will output nothing because it is searching for the variable $string INSIDE of the function, or local code block. There are a few ways we can retrieve the $string variable which is defined outside of the code block, or the $string global. A global simply refers to a variable defined in the main code block, or outside of all local code blocks. In C/C++ and other languages this term is easier to understand because globals are defined in the Main() function (or code block). However, while there is no Main() code block in PHP, the rules for globals are still very similar.

If we specify $string as a global we can call it even if it isn't defined in the code block. Let's rewrite the function.


$string = 'hey guys';
function echoString() {
global $string;
echo $string;
}

This would output "hey guys" to the user's browser. If we want to modify the actual variable that is defined outside of the function or code block, we can use the method shown above or a method involving the $GLOBALS associative array. I'll show an example using both:


$string = 'hey guys';
function modString() {
global $string;
$string .= ' this is a script using globals!';
}

modString();

echo $string;

This will output "hey guys this is a script using globals!". Be sure to call the modString() function after defining to actually modify the existing string. If you do not call this function it will do nothing since a simple function declaration doesn't output or return anything until it is called.

Now, let's look at the same thing but instead let's use the $GLOBALS array.


$string = 'hey guys';
function modString() {
$GLOBALS['string'] .= ' this is a script using globals!';
}

modString();

echo $string;

This code would produce the exact same output. It's a bit shorter, but the difference between the two is practically only preference.

Well, that's it. If you have any questions/comments or want me to explain more things or the subjects listed above more in-depth, please don't hesitate to ask!

DFox
DFox
  • Member since: Aug. 9, 2003
  • Offline.
Forum Stats
Member
Level 30
Blank Slate
Response to PHP: defining functions and stuff Jul. 23rd, 2006 @ 01:50 AM Reply

lol, I was extremely close to posting after your first post.

EXCELLENT tutorial. Very, very useful.

One thing I'd like to mention (unless I missed it), when you use return, nothing bellow the return is executed as the function is exited right away. That can be useful within loops because you might want to return something right away, which saves time. It can also sometimes help keep code less complex.


BBS Signature
Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
Response to PHP: defining functions and stuff Jul. 23rd, 2006 @ 01:52 AM Reply

At 7/23/06 01:50 AM, GamesCool wrote: One thing I'd like to mention (unless I missed it), when you use return, nothing bellow the return is executed as the function is exited right away. That can be useful within loops because you might want to return something right away, which saves time. It can also sometimes help keep code less complex.

Oh snap! I completely left that part out. Let me run over that briefly. If a function returns, nothing else is executed, period. Just like GamesCool said. Let's look at this function, it will extend the add() function and make it more professional. If the arguments being passed are not of int type the function will return false.

function add($num1, $num2) {
if ( !is_int($num1) || !is_int($num2) ) {
return false;
}

return $num1 + $num2;
}

Now, you shouldn't check the function like this:

if ( !add(0, 0) ) {
// do something
}

Because that would return a 0 value, which would make the if statement execute, but it isn't returning false. Just thought I should clear that up.

K guys, peace out.

authorblues
authorblues
  • Member since: Jun. 21, 2005
  • Offline.
Forum Stats
Member
Level 12
Blank Slate
Response to PHP: defining functions and stuff Jul. 23rd, 2006 @ 02:02 AM Reply

At 7/23/06 01:52 AM, Pilot-Doofy wrote: K guys, peace out.

might also care to mention pointers. i think the term is associative argument (cant remember). whatever the case, it allows you to send variables into a function, and whatever modifications you make to the variable occurs with the original variable. case in point:

<?
function incr(&$n){
$n++;
};

$num = 1000;
incr($num);
echo $num; // outputs: 1001
?>

the ampersand (&) is used to tell the parser that the parameter is a pointer, actually modifying the master variable from within the function.


BBS Signature
Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
Response to PHP: defining functions and stuff Jul. 23rd, 2006 @ 02:05 AM Reply

At 7/23/06 02:02 AM, authorblues wrote:
At 7/23/06 01:52 AM, Pilot-Doofy wrote: K guys, peace out.
might also care to mention pointers.

Thanks, I forgot that one too. I was basically just reading through my self defined functions and looking at the stuff I had written and touched on that. I've only used pointers a few times in my self defined functions so I didn't think to touch on them, or I forgot rather.

You did a good job at it but if someone wants more explanation I could elaborate and show more details. Functions that use these would be sort(), asort(), etc. which modify the actual variable you pass to it instead of returning the new value.

Zendra
Zendra
  • Member since: Sep. 7, 2003
  • Offline.
Forum Stats
Moderator
Level 51
Blank Slate
Response to PHP: defining functions and stuff Jul. 23rd, 2006 @ 06:32 AM Reply

Very good and well explained tutorial. This is really useful for people who're just starting with PHP. Plus the fact that you covered pretty much all of it, and the things which has been forgotten has been added later on.
Nice job. :)

Rellizate
Rellizate
  • Member since: Feb. 27, 2006
  • Offline.
Forum Stats
Member
Level 08
Blank Slate
Response to PHP: defining functions and stuff Jul. 23rd, 2006 @ 07:44 AM Reply

Great tutorial. One of the longest & best on PHP:Main in my opinion.
Keep up the good work.

;D

Pilot-Doofy
Pilot-Doofy
  • Member since: Sep. 13, 2003
  • Offline.
Forum Stats
Member
Level 37
Musician
Response to PHP: defining functions and stuff Jul. 23rd, 2006 @ 01:13 PM Reply

At 7/23/06 07:44 AM, Rellizate wrote: Great tutorial. One of the longest & best on PHP:Main in my opinion.
Keep up the good work.

;D

Thanks. Tonight when I get home I'll be explaining some other useful things dealing with advanced string manipulation, cover some bitwise operators, and show some other useful things that people often over look. For example, declaring a variable inside of an existing statement.

Well, keep your eyes open!