Funding for 'IT Lab' Project, Phase 1: Progress of sticker sales. Purchase a sticker to help us reach our target.Updated: 2010-02-28 11:53
10.7%
PHP

 by Subhash Vithanapathirana


Hi everybody! I hope you enjoyed the last article focused on control structures. In this month, you are going to learn about functions in PHP. I assume all of you have grasped the basics of PHP by referring to the previous issues. If you are not familiar with basics, it is recommended that you read them before continuing as I will not be explaining each line we talked about before.

    

   Introduction

 

As developers we write many pieces of code which could be used more than once. For example, imagine you are developing a shopping cart system. You obviously would write some logic to calculate the total cost of certain items. That might include addition of price of each product, addition of postage costs, addition of tax and maybe reduction of discounts. It can be a tedious task to write the same logic in multiple places to calculate the total cost. Apart from that, your code would become messy, unreadable and difficult to maintain.

This is where the functions become handy! A function is usually a set of commands that performs a single, well-defined task. Once you write a function, it's just a matter of calling it; just like commanding someone to do some work for you and give you the result. Isn't it interesting?

PHP has large number of functions that come built-in to it. The existence of functions for many of the commonly used actions is one great aspect of PHP. You'll be surprised to find that there is a function bundled with PHP tailor-made for most of your needs. These functions can be categorized into various types; Database functions, File system related functions, Session handling functions, Text processing functions, Image processing functions, Mathematical functions are a few of them. We will discuss about some built-in functions in upcoming issues when talking about related areas.

Today our main focus is going to be on writing your functions.

    

   User-defined Functions

 

You are not limited only to use the built-in PHP functions. In other words, you are free to write functions as per your need and make it reusable. If you are writing a block of code for a task that you likely to want to reuse in a number of places in a system, it is recommended that you write the code block as a function.

    

   Structure of a Function

 

Let's define/declare/create a simple function to start with.

<?php
function simple_function()
{
    echo "This is simple function.";
}
?>

The declaration starts with the keyword function followed by a custom name for the function. The function name you give must be something short but still descriptive. There are few restrictions for function naming as follows:

  • Function name cannot be a name of an existing function.
  • Function name can contain only letters, digits and underscores.
  • Function name cannot begin with a digit.

Ex:-

valid: myFunction(), my_function(), myfunc5()

invalid: 5myfunc(), count(), my-function()

* count() is a built-in PHP function

 

Having defined the above function, we must call it to make use of it.

<?php
simple_function
(); // prints out "This is simple function."
?>

   Parameters

 

In most of the cases, you need to pass data into the function in order to get your job done. The parameters are the way of passing data. A function can accept one or more parameters. The following function accepts two parameters; name and age.

<?php
function print_info($name$age)
{
    echo "I am " $name ", "$age years old.";
}

print_info("Tom"18); // prints out "I am Tom, 18 years old."
?>


Optional parameters

Sometimes you want to provide optional parameters to go along side with required ones. In that case, you need to define a default value for optional parameters so that the function can work with default value if it is not explicitly defined.

<?php
function favourite_color($color_name="red")
{
    echo "My favourite is " $color_name;
}

favourite_color(); // prints out "My favourite color is red";
favourite_color("blue"); // prints out "My favourite color is blue";
?>


   Returning values from functions

 

The keyword return stops the execution of a function and continues to execute the lines of code after function call.

<?php
function test_function()
{
    echo "This is line 1";
    return;
    echo "This is line 2"// This line won't be executed
}

echo 
"start";
test_function();
echo 
"more..";
?>

As you may notice this is not the most wise way of using return keyword since it skips lines given after return in any case. It is sometimes used to stop the execution when a condition is met.

<?php
function display_age($age)
{
    if($age <= 0)
    {
        echo "Invalid age";
        return;
    }
    echo "You are " $age years old.";
}

display_age(35); // prints out "You are 35 years old."
display_age(-5); // prints out "Invalid age"
?>

In above examples, we made use of return keyword to exit from the function; in other words stop execution of the function and go back to the original code. It is not the only way return keyword can be used.

If you want to pass a result back to the code from function rather than echoing the result, return keyword is used. This is a very useful and important part of writing functions.

Assuming $items parameter accepts an array containing products in a shopping cart, calcTotal() function is written to calculate the total cost of transaction.

<?php
function calcTotal($items$ship_cost$tax_rate=0.1$discount=0)
{
    $total 0;
    foreach($items as $item)
    {
        $total += $item["price"];
    }
    $total += $total*$tax_rate;
    $total -= $total*$discount;
    $total += $ship_cost;
    return $total;
}
?>

In above code, you can notice the final line returns the value of $total rather than only the return keyword. This instructs the function to give back the value stored in $total to the point of function call. This can be captured and stored in a variable to use it for different purposes. Maybe to store in a database, send an email or display on browser etc.

<?php
// construction of $items array with products purchased...
$total_cost calcTotal($items10.500.2);
// use $total_cost for different purposes...
?>

I think this article can serve as a foundation for the use of PHP functions. It is important to understand although functions make the code more readable, you are not advised to make each and everything a function. You need to decide when you should write functions and when you should not depending on the frequency and complexity of the task. Let's dig more into PHP next month, till then happy coding!


Previous Article

Post new comment

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options