Sponsored Links :
  • PHP


    Functions are arguably one of the most useful features of PHP. They allow a programmer to encapsulate sections of code within a structure which can then be executed from anywhere else in the program flow. Functions are instantiated by use of the function keyword, followed by the user-defined function name including a list of parameters between the paretheses (but we’ll worry about that in a moment) and the body of the function is contained between braces.

    Just as when defining variables, specific naming conventions must be adhered to. A function name can contain letters, numbers and underscores, and must not start with a number. They are also, like variables, case-sensitive. A (very simple) example:

    function my_function(){
      echo "Hello world";
      $a = 5;
      echo "The value of \$a is $a";
    }
    my_function();
    Hello world
    The value of $a is 5
    • Line 1 : The definition of the function. This declares that you, the programmer, have decided to create a function for use called “my_function”. The empty brackets () will be filled in later, but they are important and you cannot leave them out.
    • Lines 2-4 : Inside the braces you can place whatever code you desire
    • Line 6 : This is a function call and lets PHP know that we want to execute the function at this point. This differs from the function declaration in that we are not using the function keyword to create a function. This function call can occur anywhere within the code, as long as it occurs after the function has been declared
    <<>>

3 Responses

WP_Cloudy
  • Zach Says:

    The section containing the following:
    //begin paste from web page
    $a = 100;
    function my_function($a){
    global $a;
    $b = 10;
    echo $b+$a;
    }
    my_function(21);

    will produce

    121
    //end paste from web page

    Will actually produce 110. I know you know what you are doing, but just wanted to point out this typo to you. I am really glad you have published this PHP tutorial, I started going through it this morning and it is great. Thanks so much for putting all this together.
    Zach

  • Administrator Says:

    Ah yes, thanks for pointing that out :) I’m glad you’re finding the tutorials useful!

  • Ben Shelock Says:

    Great tutorial. Thanks :)

Leave a Comment

Want to ask a question about anything in this tutorial? Have you spotted an inaccuracy, or noticed areas for improvement? Fancy just having a chat? Leave your comments below...

Recommended Reading from Amazon.com

Previous Tutorial
Loops in PHP : While and For


Next tutorial
Reporting and handling errors in PHP