Domesticated Brain

PHP user defined functions

Before we go through the PHP user defined functions it’s better to get an idea about the functions in computer programming

 A function is a block of statements with set of instruction that can be used by the programmer to perform a specific task repeatedly in a program when they are needed.

When programming in any language, functions will allow us to save the time without typing the same pace of code again and again

A function will not be going to execute as soon as the program start. Also to execute a function we have to call that function.

The standard Syntax for PHP user defined function is:

 

function functionName() {
    code to be executed;
}

 

We can call the functions by simply typing function name and the parenthesis

 

functionName();

 

The things that we should take into account when using function names

  •  A function name can start with a letter or underscore
  • Give the function a name complying with the functions it does!

 The given below is a simple php program for php fucntions

 

<?php

 function MyFirstName(){

   echo "Shehan" ;

}

echo "My First Name is ";

MyFirstName();

?>

Out put of the above PHP program -       

My First Name is Shehan

 

PHP Function Arguments

Information can be conveyed to functions through arguments. You can add as many as arguments you want, just separating them with a comma

In the following example we are going to pass the values of the variable $num1 and $num2 to function called Addition which will echo out the sum of the both values

<?php

$num1 = 20;

$num2 = 30;

function Addition($number1,$nuber2){

       echo $number1 + $nuber2;

}

 Addition($num1, $num2);

 ?>

 

Out put of the above PHP program -       

50

 

PHP Default Argument Value

The following PHP code example shows you how to use PHP function with default arguments

<?php

function Addition($number1 = 10,$number2 = 30){

       echo $number1 + $number2 .'<br/>';

   }

Addition(10, 20);  // Here we have passed the two values

Addition();  // Here we haven’t passed any values so it will take the default values 10 and 30

?>

 

Out put of the above PHP program -

30
40

 

PHP Functions - Returning values

A function can return a value by using the return statement

<?php

function Addition($number1,$number2){

        $result = $number1 + $number2;

                   return $result;

}

echo Addition(10, 20);

?>

 

Out put of the above PHP program -

30

For more details, Please refer the PHP manual and the W3Schools web site.

If you have found  what you expected please comment and like on our facebook page