Custom Search

Monday, February 25, 2013

PHP FUNCTION


PHP FUNCTION

FUNCTION
  • A Function is a reusable piece of code. 
  • You will write it once and you can use it many times. 
  • For example, We can make a function to perform addition or subtraction or calculation of VAT, And we can use it as many times as we want. 
  • Functions have a body structure{}

 In PHP the keywords for functions are: function, return

To use a function we have two steps:
  1. function declaration
  2. function invocation (or call)


To declare a function:

you use the keyword function followed by the name of the function, two parentheses and the block of code in between two curly braces:

function fooName(parameters)
{
    // Function body goes here
    return $returnValue;
}

Functions do not have to return anything, so the return statement can be left out.

Variables used within the function are local to that function and do not effect the global scope.

  1. User defined PHP Functions
  2. zero parameter funtion

PHP Functions with Parameters:
PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like.
These parameters work like variables inside your function.
Following example takes two integer parameters and add them together and then print them.
Writing PHP Function with Parameters

function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>

This will display following result:

Sum of the two numbers is : 30

Passing Arguments by Reference:
It is possible to pass arguments to functions by reference.
This means that a reference to the variable is manipulated by the function rather than a copy of the variable's value.
Any changes made to an argument in these cases will change the value of the original variable.
You can pass an argument by reference by adding an ampersand to the variable name in either the function call or the function definition.
Following example depicts both the cases.
Passing Argument by Reference
function addFive($num)
{
   $num += 5;
}

function addSix(&$num)
{
   $num += 6;
}
$orignum = 10;
addFive( &$orignum );
echo "Original Value is $orignum
";
addSix( $orignum );
echo "Original Value is $orignum
";
?>


This will display following result:
Original Value is 21

PHP Functions retruning value:
A function can return a value using the return statement in conjunction with a value or object. return stops the execution of the function and sends the value back to the calling code.
You can return more than one value from a function using return array(1,2,3,4).
Following example takes two integer parameters and add them together and then returns their sum to the calling program. Note that return keyword is used to return a value from a function.
Writing PHP Function which returns value

function addFunction($num1, $num2)
{
  $sum = $num1 + $num2;
  return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value
?>

This will display following result:
Returned value from the function : 30

Setting Default Values for Function Parameters:
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
Writing PHP Function which returns value

function printMe($param = NULL)
{
   print $param;
}
printMe("This is test");
printMe();
?>


This will produce following result:
This is test

Dynamic Function Calls:
It is possible to assign function names as strings to variables and then treat these variables exactly as you would the function name itself. Following example depicts this behaviour.
Dynamic Function Calls
function sayHello()
{
   echo "Hello
";
}
$function_holder = "sayHello";
$function_holder();
?>

This will display following result:
Hello

PHP Built-in Functions
  • A built-in function is denoted by a function name followed by zero or more operands which are enclosed in parentheses. 
  • The operands of functions are called arguments, and each argument is specified by an expression
  • The result of a function is a single value derived by applying the operation of the function to the arguments.
  • PHP comes with many built-in (or internal) functions. 
  • We don't have to define those functions. 
  • We just need to use them, by calling their names and passing them values. 
  • PHP has nearly 3,000 built in functions covering pretty much anything you could want to do with a web application.



date() function:



   echo "". date("D") ."
";         //Day name in three letters   => Tue
   echo "". date("M") ."
";         //Month name in three letters => Dec
   echo "". date('l, jS F Y')."
"; //Day, date Month Year => Monday, 23 March 1920
?>




  Here some examples of functions to use to handle form data:

/*

   strval(intval($variable))  //STRVAL gets the string value of a variable
   strval(floatval($variable))  //INTVAL and FLOATVAL get the integer/float value of a var
   addslashes($variable)       // Escape single quote with a back slash
   stripslashes($variable)     // Escape back slash from string
?>
*/

Using print_r():


   $arr = array("a"=>"dog",
                      "b"=>"cat",
                      "c"=>"horse",
                      "reptiles"=> array("snakes", "lizards", "turtles")
  );

  echo "
";

  print_r($arr);

  echo "
";

/*

Array
(
    [a] => dog
    [b] => cat
    [c] => horse
    [reptiles] => Array
        (
            [0] => snakes
            [1] => lizards
            [2] => turtles
        )

)
*/
?>

Using mail() to send an email:

   //to send an email
   mail($to, $subject, $message, $from);
   echo "Thank you for sending email";
?>


No comments:

Post a Comment