Functions in PHP

This article shows PHP functions that include the following:

  • Invoking function
  • Send parameter to function
  • Type hinting
  • Return multiple values

Invoking a function

We can invoke a function by simply specifying function name if it is already defined in the library.

For example the pow() function is used to calculate the power of a number.

  1. <?php  
  2.    $value = pow(5, 2); // returns 25  
  3.    echo $value;  
  4. ?>  
Or we can simply output data in the screer:
  1. <?php  
  2.    echo pow(5, 2); //returns 25  
  3.   
  4. ?>  
Or

echo "Five square equals to ".pow(5,2); ?>

Creating a function

In PHP the function pseudo code looks as in the following:
  1. function function_name(parameter)  
  2. {  
  3.    //Function body  
For example:
  1. <?php    
  2. function fun($para
  3. {  
  4.    echo " you are inside function fun which has parameter $para";  
  5. }  
  6.   fun("hello");  
  7. ?>  
Output

you are inside function fun which has parameter hello

Preceding function argument is passed by value in which any changes made inside the function are ignored outside the function.

Pass by reference: Here changes inside the function take effect outside the function as seen in the following example with the $cost variable being passed using a reference using ‘&’ in the function calculatePrice().
  1. <?php  
  2.    $price = 21;  
  3.    $tax = 0.275;   
  4.    function calculatePrice(&$price$tax
  5.    {  
  6.       $price = $price + ($price * $tax);  
  7.       $tax+= 6; //some updating in $tax so the output changes outside function  
  8.    }    
  9.    calculatePrice($price$tax);  
  10.    printf("Tax is %01.2f%% "$tax * 100);  
  11.    printf("Price is: $%01.2f"$price);  
  12. ?>  
The output is:

Tax is 27.50% Price is: $26.77

Default argument

A default argument is used when no value is passed to an argument of a function. A default value is then assigned to the argument, for example:
  1. <?php   
  2.    function func($var1$var2 = "hello")  
  3.    {  
  4.       echo $var1$var2//here $var2 takes default argument which is “hello”  
  5.    }    
  6.    func("hello ");  
  7. ?> 
The output is:

hello hello

It gives the following error if you don’t provide an argument for the function.

Missing argument 2 for func(), called in C:\xampp\htdocs\ex.php:
  1. <?php  
  2.   
  3.    function func($var$var1)  
  4.    {  
  5.       echo $var$var1;  
  6.    }  
  7.    func("hello");  
  8. ?>
Type Hinting

PHP5 introduces a new function type hinting that forces the parameter of a function to be an object of a certain class or to be arrays. We can’t use a scalar data type with it. If the type doesn’t match then it will return a fatal error.

See an example to understand this:
  1. <?php  
  2.    class cat    
  3.    {  
  4.       public  
  5.   
  6.       function do_drool()  
  7.       {  
  8.          echo " This is cat class\n";  
  9.       }  
  10.    }    
  11.    class dog   
  12.    {  
  13.    }    
  14.    function drool(cat $some_cat)  
  15.    {  
  16.       $some_cat->do_drool();  
  17.    }      
  18.    $poppy = new cat();  
  19.    drool($poppy);  
  20. ?>  
This gives the output:

This is cat class

Explanation of the preceding example: If we use the dog class then it simply gives a fatal error because of type mismatch. We must pass an argument of type class cat.

The return Statement

The return statement returns the value to the caller function and also returns the execution control to the caller program. If return() is globally called then it's specific script execution is terminated.

Example
  1. <?php   
  2.    function fun($para)  
  3.    {  
  4.       echo " you are inside function fun which has parameter $para";  
  5.       return " hello";  
  6.    }   
  7.    echo fun("hello");  
  8. ?>  
This gives the following output:

hello hello

Return Multiple Values in PHP

In PHP sometimes we need to return more than one value and this can be done using a very simple construct, list(). The list() construct gives a method for retrieving values from an array as in the following:
  1. <?php    
  2.    function names()  
  3.    {  
  4.       $user[] = "sandeep";  
  5.       $user[] = "pankaj";  
  6.       $user[] = "rahul";  
  7.    return $user;  
  8.    }    
  9.    list($user1$user2$user3) = names();  
  10.    echo " user1: $user1, user2: $user2, user3: $user3";  
  11. ?>  
This gives the output:

user1: sandeep, user2: pankaj, user3: Rahul

Function Libraries

If we want to make a library of our own defined functions then it is useful to directly include that file with any of the statements that include_once(), include() , require_once() etc.

For example, if we make a file that calculates various taxes then save this file as tax.library.php and then include it in any of your files as:
  1. <?php  
  2.    include (tax . library . php);    
  3.    // ………… code  
  4. ?>  
And we can simply retrieve that function directly by its function name.

Note: We can see a PHP function list by visiting the official PHP site at www.php.net and use the documentation. If we know the function name like power, we can go directly to the function’s page by appending the function name onto the end of the URL. For example, if we want to learn more about the pow() function, go to www.php.net/pow and this will provide direct information about the power function.

Summary

In this article we see reusability of code using a functional approach in PHP. We learned how to invoke functions, pass arguments among functions and aggregate functions into libraries.

Up Next
    Ebook Download
    View all
    Learn
    View all