PHP function is a piece of code that can be reused many times in program. In php there are different type of functions, we are using these functions depending upon their need and uses.
Advantage of using functions :
- Code Reusability : PHP functions are defined only once and that can be used anywhere in programs
- Easy To Understand : PHP functions support the modular design and that enables user to separate the programming logic depending upon their need. Also this helps to understand the programming flow of application better as it works on modular design.
- Less Code : we don't have to write the same code or same logic many times. Reusability functionality makes the programming block short, simple and precise.
- Save Time : it is saving the time as user only reusing the same functional block rather writing the same code again.
Create user-define function in PHP:
Syntax :
function functionName() { code to be executed here; }
Steps to remember while designing functions :
- A function name can start with a letter or underscore (not a number).
- Give the function a name that reflects what the function does.
- The opening curly brace ( { ) indicates the beginning of the function code and the closing curly brace ( } ) indicates the end of the function.
- Function names are case-insensitive.
Simple Function Example :
<?php function displayMessage() { echo "Welcome to php function example"; } displayMessage(); // call the function ?>
Output:
----------------------
Welcome to php function example
PHP Function Arguments :
lets see the single argument function example in php.
<?php function displayName($name){ echo "Hello $name<br/>"; } displayName("Amit"); displayName("Skptricks"); displayName("Wayplus"); ?>
Output :
-------------------
Hello Amit
Hello Skptricks
Hello Wayplus
Hello Skptricks
Hello Wayplus
lets see the two arguments function example in php.
?php function displayName($name,$salary){ echo "Hello $name, you salary is $salary INR <br/>"; } displayName("Amit",20000); displayName("Skptricks",4000); displayName("Wayplus",50000); ?>
Output:
-------------------
Hello Amit, you salary is 20000 INR
Hello Skptricks, you salary is 4000 INR
Hello Wayplus, you salary is 50000 INR
Hello Skptricks, you salary is 4000 INR
Hello Wayplus, you salary is 50000 INR
Function Returning Value :
<?php function add($a,$b){ return $a+$b; } echo "sum of two numbers is ".add(3,9); ?>
Output:
-----------------------------
sum of two numbers is 12
No comments:
Post a Comment