• home
  • forum
  • my
  • kt
  • download
  • Functions in PHP

    Author: 2009-03-09 10:17:27 From:

    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

    Global and Local Scope

    Scope is defined, within the realms of PHP, to mean the context within which a variable, or a function is defined. For the most part, any variable defined within the flow of a program is available throughout the rest of that program, or within the global scope of the program. There are a few cases where scope changes though, and one of these is when entering a function definition.

    You can think of functions as self-contained sections of code, and while writing a function, you don’t need to worry about what might be happening outside the function definition, you can concentrate on its inner workings. Every function has its own scope inside which, variables are “hidden from the outside world”, and vice-versa.

    More precisely, any variables which you declare within the function will not be available from outwith the function. So, the following code

    function my_function(){
      $a = 5;
    }
    echo $a;

    produces

    That’s right, nothing! (PHP by default treats undefined variables as if they are null, or blank) This also happens in reverse. Let’s try referencing a variable created outside a function from inside the function

    $b = 20;
    function my_function(){
      echo $b;
      $b = 10;
      echo $b;
    }
    my_function();

    produces

    10

    Here, we only see the value of $b that was created inside the function. From the function’s point of view, when we reference $b in line 3, it doesn’t exist. We can fix this by use of the global keyword

    The use of the “global” keyword

    $b = 20; //defined in the "global scope"
    function my_function(){
      global $b;
      echo $b;
      $b = 10; //assigns $b = 10 _in the global scope_
      echo $b;
    }
    my_function();
    echo $b;

    produces

    20
    10
    10

    Here, the use of “global” tells the function to use the version of $b that has been defined globally, that is, the version that has been defined outside the function but within the same scope as the function definition.

    You might wonder though, why the value of $b in line 9 is printed as “10″. That’s because, by defining $b as global within the function, we are telling the function to treat any expression assigning $b a value (such as “$b = 10″ on line 5) to be working with the global variable $b, and not a local variable.

    Function Parameters

    Let’s get back to the function definition now, and explore that a little further. Specifically, let’s look at that pair of parentheses () which was empty in our initial function declarations. We’ll now move on to see what happens when we fill this space up with variables

    function my_function($a){
      $b = 10;
      echo $b+$a;
    }
    my_function(21);
    my_function(10);

    Here, you’ll see on line 1, we’ve introduced the variable $a into the function definition, but this isn’t treated as a variable in the same way we’ve seen so far. Instead, the definition of $a here is treated as an argument to the function, and this means that the function can now accept user values defined at the time of the function call (in lines 5 & 6 in the above example)

    The above code will produce the output

    31
    20

    because, as you can see, we’re passing the values 21 and 10 as arguments to the function, and these arguments are then assigned as locally defined variables within the scope of the function. Let’s see what happens when we reintroduce the “global” keyword here

    $a = 100;
    function my_function($a){
      global $a;
      $b = 10;
      echo $b+$a;
    }
    my_function(21);

    will produce

    110

    The globally defined $a over-rides the locally defined $a, so you can see there how variable scope affects the execution of PHP code if you’re not careful

    Passing Variables Into Functions

    We can also pass the values of variables into functions, and this is a very useful way of creating PHP code where functions are used to perform complex calculations on values. Here, we’ll also make use of the “return” keyword, to return a value from the function. This essentially turns the function into a calculator which can take in values, and also output values back into the program

    Note that it doesn’t matter what the name of the variable is that you pass into the function, since the function will recreate the value of the variable within its body, and assign it a locally defined name.

    1
    2
    3
    4
    5
    6
    7
    
    function my_function($a){
      $a = $a + 100;
      return $a;
    }
    $x = 100;
    $result = my_function($x);
    echo $result;

    This produces

    200

    Here, we are assigning the value of 100 to the variable $x in line 5. We are then passing the value of $x (100) into the function, where it is accessible via the locally defined variable $a. We then add 100 onto the value of $a in line 2, and then line 3 is where we introduce the return keyword.

    The “Return” Keyword in Functions

    Return is used when we wish to end the execution of a function and return a result. Any code inside the function placed after a return statement will not be executed. Instead, program execution returns to the point where the function call was started. In this case, returning to line 6, where the value of the function is assigned to the variable $result.

    1
    2
    3
    4
    5
    6
    7
    
    function my_function($a){
      $a = $a + 100;
      return $a;
    }
    $x = 100;
    $result = my_function($x);
    echo $result;

    The value of the function here is equal to the value of $a on line 3, at the point when the return statement was called. $a equals 200 here, and so the function returns the value “200″ for storage inside the $result variable.

    When passing variables to functions, there are more things to consider though, and the calculation potential of functions isn’t just limited to processing numbers. In the next few sections, I’ll outline how you can use functions to take greater control over the contents of your data structures, and also to process more complex information.

    Passing By Reference and Passing By Value

    The above example is a case of “passing by value” into a function declaration. But what does that mean? Simply put, it means we were passing the values “21″, “10″ or “100″ into the function for processing. This would work for any other type of variable, you could pass the string value “Hello world”, or the floating point number 1.2345. The only exception here is with arrays, and we’ll cover the behaviour of those in a future tutorial

    What is meant by “Passing by reference” though, the opposite of “Passing by value”? If you remember, I mentioned in the earlier tutorial about variables, that it’s possible to reference the address of a variable, rather than the value contained within the variable. The same can be said of the parameters list for functions. Take this example
    [make this less confusing...]

    function my_function($a, &$b){ //$b passed _by parameter_
      $b = 10;
      $b = $b+$a; //if $b was passed _by value_ this wouldn't affect the global definition of $b=100
    }
    $x = 100;
    my_function(21, $x);
    echo $x;

    This will produce the output

    31

    Possibly a slightly unexpected result? Indeed, you may think so. But consider this - by defining the second argument to the function as &$b we are saying that the function shouldn’t accept the value of $b as an argument, but should instead accept $b itself, and perform any calculations on the variable as if it were globally defined. If we were passing by value (and not by reference) we would ensure that the value of $b was not changed outside the function. But by passing by reference, we can allow the function to alter the value of $b within the global scope.

    An important point to make here is that you can’t pass a value by reference. So, for example, the following code

    function passed(&$a){
      echo $a;
    }
    passed(5);

    will fail, but the code

    function passed(&$a){
      echo $a;
    }
    $x = 5;
    passed($x);

    will work without a problem (note how we’re passing the address of the variable $x in the second example. In the first example, the value 5 cannot have an address, since it cannot have an address location

    discuss this topic to forum

    relation tutorial

    No information

    Category

      Ad Management (6)
      Calendars (3)
      Chat Systems (8)
      Content Management (41)
      Cookies and Sessions (12)
      Counters (15)
      Database Related (34)
      Date and Time (15)
      Development (22)
      Discussion Boards (8)
      E Commerce (8)
      Email Systems (14)
      Error Handling (8)
      File Manipulation (36)
      Flash and PHP (6)
      Form Processing (22)
      Guestbooks (12)
      Image Manipulation (26)
      Installing PHP (7)
      Introduction to PHP (28)
      Link Indexing (8)
      Mailing List Management (9)
      Miscellaneous (53)
      Networking (8)
      News Publishing (9)
      OOP (24)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (6)
      Postcards (1)
      Randomizing (14)
      Redirection (11)
      Searching (9)
      Security (29)
      Site Navigation (16)
      User Authentication (14)
      WAP and WML (7)
      Web Fetching (8)
      Web Traffic Analysis (15)
      XML and PHP (16)

    New

    Hot