In: Tutorials / PHP

Functions

Create and use your own PHP functions.

Print
Author: Dyllon
Submitted by: Brock   Date: 2008-03-09 18:54
Comments: (0)   Ratings:
No comments yet
Information

This tutorial will show you how to create and make use of your own functions. Functions can come in handy a lot for webmasters, because it saves a lot of code and space.

How to create a function

Before you try to create your own function, you must first think about exactly how it is going to work completely. Heres a very basic function:

Code:
function get_user_avatar($userid)
   {
   global $db_users

   $sql = sed_sql_query("SELECT * FROM $db_users WHERE user_id='$userid'");
   $row = sed_sql_fetcharray($sql);

   $result = "<img src=/"".$row['user_avatar']."/">";

      return($result);
   }
This is a function I made a while back for my site. I needed a quicker way to get users avatars, so I made this one really quick. Now, I'll explain how I made this.

1. Every function first needs a name. Mine I chose get_user_avatar

2. Following the name are the inputs that you put into the function. These are not required, however, for this one I needed one which was $userid. So, whichever userid we enter into this, the result will be that user's avatar.

3. Now, I queried the database with the user id to find out the users avatar, and stored it in the variable $result.

4. Once you're done with the variable to show the output, you need to add: return($variable); which for us was: return($result);

How to use a Function

In order to use this function, now we need to find the appropriate place. I used it for a custom plugin, however anywhere will do. So lets say I use it in the user's details. To call this function, I would simply add anywhere in the code: get_user_avatar(1); and this will get me my avatar.

Hope this short one helped out a bit :)