Jump to content

  •  

  • iBotModz CBox


    Photo

    Beginning PHP - Lesson 21 - Making your own Functions


    This topic has been archived. This means that you cannot reply to this topic.
    No replies to this topic

    #1 fattwam

    fattwam

      General Grade 2

    • Sub-Admins

    • 3,979 posts
    • Joined: 18-August 07

    Posted 27 March 2008 - 08:27 PM

    I want to teach you how to make your own functions now. We have been using lots of PHP's built-in functions, but did you know that you could make your own?

    A function is basically a command that tells the computer to carry out a certain set of instructions for you. For example:

    trim() - Strips white spaces from the begging and end of a string.
    mysql_query() - sends a MySQL queary.
    count() -- Counts the elements in an array, or properties in an object
    crypt() -- One-way string encryption (hashing)
    file() -- Reads an entire file into an array

    These are all functions that people wrote to do these tasks for you rather than you having to build a bunch of loops or classes every time you want to do these things. With these functions all you do is:

    $newstring = trim($string);
    ?>


    As a pose to trying to write all of the code that would trim the $string:

    foreach(count($string) as $var) {
    blah... blah... blah
    .....
    blah... blah... blah
    .....
    blah... blah... blah
    .....
    while ($x > $something) {
    blah... blah... blah
    .....
    blah... blah... blah
    .....
    blah... blah... blah
    .....
    blah... blah... blah
    .....
    }
    ....
    more code....
    ....
    blah... blah... blah
    .....
    blah... blah... blah
    .....
    }
    ?>



    Well, if other people can make functions why can't you? Well...You can! So lets get to it!


    Here is the syntax for making a function:
    function fakefunction($argument_1, $argument_2, /* ...more arguments..., */ $argument_n)
    {
    echo "Example function.n";
    return $returnvaliable;
    }
    ?>


    The first step is to type "function", this lets the computer know that you are going to make a function. Next you create a name for the function, we choose "fakefunction".

    NOTE: You want to be careful when you choose the name because there might already be a function by that name. If you want to find out if the name already exists visit the function index at php.net.

    After you choose a name you need to decide if there are going to be any arguments passes to the function. An argument would be like a variable:


    function does_user_exits($username) {
    run code to see if "username" exists
    }
    ?>


    If you didn't pass the function does_user_exits() the variable "$username" how would you be able to see if that user existed?

    A real-life example is trim():

    $newstring = trim($string);
    ?>


    If you didn't pass the function the name of the string too trim, what good would it do?

    Finally, you add all of the code that will make up the function and then when your done you let PHP know your finished by typing a closing " } ". So now lets get to it!


    ##########################################################
    ## PART 2: Making a function
    ##########################################################

    Open up SciTE or Notpad and type this into it:



    function print_my_name() {
    echo "My name is David";
    }

    print_my_name();
    ?>

    Note: I hope you changed David to your name... :wink:

    Save the file as "printname.php" and upload it to your server. When you run "printname.php" you will see:

    My name is David


    Now then, you have just made your first function! Give yourself a pat on the back.
    When the function print_my_name() is called it will run the code inside it. However, the only code is one line that prints out "My name is David".

    Also, realize that after you make the function you have to call it! Just because you wrote the function doesn't mean that it will run. You have to now tell PHP when and where you want that function to run. In this case we told the computer to run the function right away:


    print_my_name();


    However, we could have waited until later in the script or even not run it at all!

    ##########################################################
    ## PART 3: Making a USEFUL function
    ##########################################################

    Open up SciTE or Notepad and type the following into it:



    function print_out_file($filename) {
    // Read file into array called $contents
    $contents = @file($filename);

    //if the array isn't empty (a.k.a. there was something in the file!)
    if (count($contents) > 1) {

    // Loop through the array and print out the line (with a line-break (
    ))
    foreach ($contents as $row)
    {
    echo "$row
    ";
    }
    } else {
    // if $contents is equal to '0' or there was an error opening the file print:
    echo "File is empty or doesn't exist!";
    }
    }

    ?>


    You can now save it as "file_functions.php" and upload it to your server. Next, start a new document and type this into it:


    include ("file_functions.php");
    print_out_file("testfile.txt");
    ?>


    Then save it as "printfile.php" (or whatever you want to call it) and upload it to your web server. Open your browser and go to "printfile.php". When you do you should get a nice error message saying:

    File is empty or doesn't exist!

    Can you figure out why? (Hint: read the error )


    That's right! There IS no file called "testfile.txt"! So start your editor one more time and type five lines of anything you want into it:


    This is line One.
    This is line Two.
    This is line Three.
    This is line Four.
    This is line Five.

    Save it as "testfile.txt" then upload it to your web server. Once all three are on the internet (and in the same directory) open your browser and go to "printfile.php".


    This time you have passed a file that actually exists to your function and it was able to open the file. So you should see this on the screen:


    This is line One.
    This is line Two.
    This is line Three.
    This is line Four.
    This is line Five.



    Now then, you have just made your first useful function! Give yourself another pat on the back, lol.
    I trust you understand the code inside the function. If not, you need to read the past lessons . So onto the description of what is going on here:

    First we made the file "file_functions.php" and we created a function called "print_out_file()". That function is only passed one argument - the name of the file to print out.

    Then we made "printfile.php" which was a simple two line script that included "file_functions.php" and then ran the function. Because the function is in it's own file we can now use print_out_file() in any script we want simply by including the file "file_functions" and then typing print_out_file().


    SIDE NOTE:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

    By making the function and putting it into its own file we can keep our code clean. Imagine if we had a large function in the middle of a good-sized script. If we were trying to find an error it would be a pain to search the whole document.

    Note: Just for those who would like to see it - here is what the file would look like if we stuck the function into "printfile.php":



    function print_out_file($filename) {
    // Read file into array called $contents
    $contents = @file($filename);

    //if the array isn't empty (a.k.a. there was something in the file!)
    if (count($contents) > 1) {

    // Loop through the array and print out the line (with a line-break (
    ))
    foreach ($contents as $row)
    {
    echo "$row
    ";
    }
    } else {
    // if $contents is equal to '0' or there was an error opening the file print:
    echo "File is empty or doesn't exist!";
    }
    }

    print_out_file("testfile.txt");

    ?>


    While this would work just fine; like I said, by sticking the function in it's own file it keeps the code clean for larger scripts.

    Plus, by having the function in it's own file any script on our server can use the function by just including the file!

    ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


    Ok, that's it! Try making your own functions for things you do often! For example I put the entire HTML Header and Footer for my pages into two functions called page_header() and page_footer() then have all of my pages just include the function.php page and then I run page_header() and page_footer():


    include("functions.php");
    page_header();


    // Main content here



    page_footer();
    ?>



    Peace!