Showing posts with label pre-processors. Show all posts
Showing posts with label pre-processors. Show all posts

Wednesday, 10 February 2016

Definitions and use of function

Definitions and use of function.

A function is a group of code which takes one or more parameter/arguments, and after process, give return a value. A function will not execute until we call to the function.

Note: A function name can not a number.

Syntax:

function YourFunctionName( )
{  
    STATEMENTS 1;
    STATEMENTS 2;
    STATEMENTS 3;

}

What is Arguments?

An argument is a variable, which is passed in functions. You can pass many parameter ( or argument) in a function (separate with a comma).

Example: 

function  NameAge ( $name, $age ) 
{
    echo "$name age = $age";
}
in this example, only pass two parameter, like this you also pass more parameter according your request.

What is Default Argument in a function?

If you call the function without argument value, then it takes the default value as this argument.
Example: 

<?php
function  NameAge ( $name, $age=20 ) 
{
    echo "$name age = $age";
}

NameAge ("Rakesh");           // output:  Rakesh age = 20
NameAge ("Rakesh","28");  // output:  Rakesh age = 28

?>

In this Example, $age=20 is  default argument  if we not pass any age, then its take $age=20.

Different  types of functions in PHP.


  1. User defined function
  2. Return value function
  3. Variable function
  4. Anonymous function

User defined function

Normally, all kinds of useful functions built-in PHP library. But if a function not find in PHP library. Then PHP allows you to build your own functions.

Tip:"Give the function a name that reflects  the function work"

<?php
  function myFirstFunction()
 {
    echo "This is My Function";
  }
?>

Return value function 


Return value function, return a value according to argument, with return statement.

<?php
  function addTwoNo($a, $b) {
    $total = $a + $b;
    return $total;
  }
 echo $sum = example(20, 30);
?>

Variable function

PHP supports the concept of variable functions. This means that if a variable name has parentheses appended to it, PHP will look for a function with the same name as whatever the variable evaluates to, and will attempt to execute it. Among other things, this can be used to implement callbacks, function tables, and so forth.

<?php
    $func = "sqrt";
    print $func(7);
?>

Hear we see that PHP are calling a function using a variable, 

Anonymous function

An anonymous function is simply a function with No Name.
An anonymous function has no name so you would define it like this:
<?php
function () {
  return "Hello PHP";
}
?>