Thursday, May 7, 2020

Functions in PHP

  • A function is a reusable piece or block of code that performs a specific action.
  • Functions can either return values when called or can simply perform an operation without returning any value.
  • In PHP, we can define Conditional function, Function within Function and  Recursive function also.
  • PHP has over 700 functions built in that perform different tasks.

Why use Functions?

  • Better code organization – functions allow us to group blocks of related code that perform a specific task together.
  • Reusability – once defined, a function can be called by a number of scripts in our PHP files. This saves us time of reinventing the wheel when we want to perform some routine tasks such as connecting to the database
  • Easy maintenance- updates to the system only need to be made in one place.

Built-in Functions

Built in functions are functions that exist in PHP installation package.

These built-in functions are what make PHP a very efficient and productive scripting language.

PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts to perform a specific task, like gettype(), print_r(), var_dump, etc.

PHP User-Defined Functions

In addition to the built-in functions, PHP also allows you to define your own functions. It is a way to create reusable code packages that perform specific tasks and can be kept and maintained separately from the main program

The basic syntax of creating a custom function can be given with:

function functionName(){
    
// Code to be executed
}

The declaration of a user-defined function start with the word function, followed by the name of the function you want to create followed by parentheses i.e. () and finally place your function's code between curly brackets {}.

Let’s now create our first function. We will create a very basic function that illustrates the major components of a function in PHP.

<?php
//define a function that displays hello function
function add_numbers(){   
        echo 1 + 2;
}
add_numbers ();
?>

Output:

3

  HERE,

  • “function…(){…}”  is the function block that tells PHP that you are defining a custom function
  • “add_numbers” is the function name that will be called when using the function.
  • “()” can be used to pass parameters to the function.
  • “echo 'Hello function!';” is the function block of code that is executed. It could be any code other than the one used in the above example.

Functions with Parameters

Let’s now look at a fairly complex example that accepts a parameter and display a message just like the above function.

Suppose we want to write a function that prints the user name on the screen, we can write a custom function that accepts the user name and displays it on the screen.

The code below shows the implementation.

<?php
function display_name($name)
{
echo "Hello " . $name;
}
display_name("Martin Luther King");
?>

Output:

Hello Martin Luther King

  HERE,

“…($name){…” is the function parameter called name and is initialized to nameless. If no parameter is passed to the function, nameless will be displayed as the name. This comes in handy if not supplying any parameter to the function can result in unexpected errors.

Let’s now look at a function that accepts a parameter and then returns a value. We will create a function that converts kilometers to miles. The kilometers will be passed as a parameter. The function will return the miles equivalent to the passed kilometers. The code below shows the implementation.

<?php
function kilometers_to_miles($kilometers = 0)
{
$miles_scale = 0.62;
return $kilometers * $miles_scale;
}
echo kilometers_to_miles(100);
?>

Output:

62

Functions with Optional Parameters and Default Values

You can also create functions with optional parameters — just insert the parameter name, followed by an equals (=) sign, followed by a default value, like this.

<?php
// Defining function
function customFont($font, $size=1.5){
    echo "<p style=\"font-family: $font; font-size: {$size}em;\">Hello, world!</p>";
}
// Calling function
customFont("Arial"2);
customFont("Times"3);
customFont("Courier");
?> 

As you can see the third call to customFont() doesn't include the second argument. This causes PHP engine to use the default value for the $size parameter which is 1.5.

Passing Arguments to a Function by Reference

In PHP there are two ways you can pass arguments to a function: by value and by reference. By default, function arguments are passed by value so that if the value of the argument within the function is changed, it does not get affected outside of the function. However, to allow a function to modify its arguments, they must be passed by reference.

Passing an argument by reference is done by prepending an ampersand (&) to the argument name in the function definition, as shown in the example below:

<?php
/* Defining a function that multiply a number
by itself and return the new value */
function selfMultiply(&$number){
    $number *= $number;
    return $number;
$mynum = 5;
echo $mynum// Outputs: 5
 
selfMultiply($mynum);
echo $mynum// Outputs: 25
?>