PHP Variables Functions( )
In this chapter we will learn about PHP functions( ). Most of the beginners always think, why we create functions and how does it help to the program? We create functions to make the program easier and smaller. It prevents the programmer from writing the same code again and again. A program contains several functions that can be used several times . A function escape the program from being complex and it compiles and run efficiently, which save the time of the programmer. It also makes the program easier. For defining a function we need to remember some important points:
(a) Always give name to the function. The function should start with name or underscores. It doesn't take numbers in the starting of the function name. Such as func_name, _funcname or name1.
(b) Don't forget the parentheses ( ).
(C) In between opening and closing braces return your statements.
Now, look at few examples and understand how functions are beneficial for a programmer.
function my_favorite( )
echo "Sachin Tendulkar"; /* statement */
echo "My favorite cricket player is ";
The output of the above example is:
My favorite cricket player is Sachin Tendulkar
In this example, we give the name or define to a function called my_favorite( ). In the statement we written Sachin Tendulkar and then called the function after the closing braces.
PHP Function - Passing Parameters ( )
PHP function also provides the facility to pass the parameters in the program. It means we are adding more functionality in our program. It is similar to the variable and you can fetch as much as information you want. For example :
<?php function func_name($name)
echo $name . " " . " Tendulkar " . "<br/>";
echo "My name is ";
echo "My younger brother name is ";
echo "My elder brother name is ";
In this example we are passing parameters in the parentheses.
PHP Functions - Return value ( )
With the help of return statement in PHP we can ask the program to return some value either in the form of int, float, array, string etc which one you are looking for.
$total = $num1 + $num2;
$num1 = "100";
$num2 = "200";
echo " $num1 + $num2 = " . $total = sum($num1,$num2);
Posted on: January 9, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles