Functions is a block of code that is executed when we need to execute it.
Why we need functions:-
Functions are used whenever we want to use same block of code within our program whenever we need, instead of writing same code again and again it is better approach to make its function.
Types of functions:-
Normally there are two types of functions
- Builtin Functions
- Userdefined Functions
Builtin Functions:-
Some functions are already written and defined by programming language itself, means they are already built, just need to call them whenever u use it, these functions are called builtin functions. Like mysql_num_rows() is a builtin function that tell u about no of rows.
Userdefined Functions:-
Userdefined Functions are those functions that are defined and declared by programmer, means programmer write these functions whenever he wants. Below in examples we are dealing with Wserdefined Functions.
How to create functions in php?
- Function should start with the word function.
- Function name should be logical, means if you want to make function to add numbers, write its name add() or sum()
Function defining and function calling:-
Function defining is a process in which we define our function that is use later. To use a function in a program we just use the term calling a function. Whenever we want to use any function we just call it.
function consists of two parts
Example 1:- A simple function
function HelloWorld()
{
echo "Hello World";
}
How to call this function?
Lets make a php script and use this function
function Hello()
{
echo "Hello World";
}
echo "Just want to say
";
Hello();
Output:-
Just want to say
Hello World
Adding Parameters to the function:-
The above function Hello() is a very simple function because its only displaying static string. To make function more handy we can add parameters to the function. A parameter is worked like a variable. The parameters are used inside the function parentheses
Example 2- Function with parameters
function Hello($mystring)
{
echo $mystring;
}
echo "I just want to say
";
Hello("Hello php programmers");
Output:-
I just want to say
Hello php programmers
Note:- It's up to you, how many parameters you used in a function.
Get values return by function
Function can also return values, it can return nothing or some values, its up to their use.
Function dosum($a,$b)
{
$sum=$a+$b;
return $sum;
}
echo "sum is".dosum(1,2);
Output:-
sum is 3
0 comments:
Post a Comment