PHP FUNCTIONS
Hello All...
welcome every one. I'm going to start PHP lectures for Very Beginners, who
wants to learn PHP from very beginning. No matter if you do not have any basic
programming concept. If you follow my tutorials I hope you will surely get some
how good knowledge of PHP.
Today our
Topic is
FUNCTIONS
We use
functions for avoiding repetition of code again and again. We write our code
within a certain block and name that block, so whenever we need the same code
we just call that name not the whole code to be repeated again.
Much like
variables function name is declared with same patterns but not starts with $
sign. Here is how we create a function.
<?php
function function_name(){
echo “this is function example”;
}
function_name();
?>
First of all
write function keyword, besides that give a name to this function with open and
close braces then start and close the curly brackets and inside that curly
brackets you can write your code whatever you want, I have just echo a
statement further you can write loops, if conditions or anything else.
Now to
display what is written inside the function body we call that function, by
writing just the name of the function. But remember call the function outside
the function body. How much times you call name of function so many times the
result will come out. Look for another example.
<?php
function addition(){
$num1 = 20;
$num2 = 30;
echo $num1 + $num2;
}
addition();
?>
The result
will be 50, if again you call function name such as,
addition();
addition();
it will
generate `5050`. Similarly in this way you can put your every code just like
conditions, operators, loops inside the function and for output just call the
function name.
From the top
you are declaring the function and in the bottom you are calling the function
for output.
ð Passing Values
To a Function
If you want
to give dynamic values for output you can pass values to a function by putting
the values between the parentheses when you call the function.
Look for an
example
<?php
Function pass_value ($var1, $var2){
echo $var1 + $var2;
}
pass_value(20,30);
pass_value(40,50);
pass_value(50,50);
?>
Firstly
declare any variables you want. In echo statement just write the code you want
to execute and the values you will be giving within the braces while calling
the function and no matter how many times you call the function and whether you
give same values or different the result will be according to your values you
are given.
Above declared
variables within function braces are called as parameters, and the values given
in last while calling function are called Arguments.
Note that
sequence and the quantity of the Parameters and Arguments should be the same
otherwise it’ll generate the wrong result.
Thanks Guys.
Any thing missing or any question from this topic you can comment below, I will
be trying to solve and answer your question.
Our Next
topic will be `Built-in Functions `.
Good Luck J
No comments:
Post a Comment