Monday 28 November 2011

User Defined function


A function is a block of code that can be executed whenever we need it

Ø       Creating user define function

Syntax

                        function  function-name($argument1,$argument2……..$argumentn)
                   {
                             Code  to be executed
                   }

  • All function start with the word function “function()”.
  • Name the function – it should be possible to understand what the function does by its name the name can start with a letter or underscore.
  • Add a “{” – the function code starts after the opening array bracket.
  • Insert the function code.
  • Add a “}” -  the function is finished by a closing curly bracket.

Example

<?php
          function left()
          {
                   echo "Hello World";
          }
          left();
          ?>


Output

Hello World

Ø       Argument function

  • Information may be passed to function via the argument list, which is a comma-delimited list of expression.
  • PHP supports passing argument by value, passing by reference, and default argument values.

Example

<?php
          function test($a)
          {
                   echo "Value of A is $a";
          }
          test(10);
          ?>

Output  

Value of A is 10

Ø       Default function

Using PHP there can be function made which can have some default value in the variable of argument. When the function is called if no argument is passed then it will return the default value which Is set in function definition else will overwrite the value which is passed.

Example

<?php
          function test($a=10)
          {
                   echo "Value of A is $a";
          }
          test(20);
          ?>

Output  

Value of A is 10

Ø       variable function

PHP support the variable function. This means that if the variable has the value of the function name and if the function is called using that variable then it will call the function having the value same as function name.

Example

<?php
          function test($a)
          {
                   echo "Value of A is $a";
          }
          $value = "test";
          $value(20);
          ?>

Output  

Value of A is 20

Ø       Return function

This type of function takes some argument and does return the value. When the value is returned by the function it is required that when the function is called the variable should be there to accept the returned value from the function.

Example

<?php
          function add($a,$b)
          {
                   $c = $a+$b;
                   return $c;
          }
          $value =add(10,20);
          echo "Addition : ".$value;
          ?>

Output  

Addition 30

Posted By : Hemangi Zala

No comments:

Post a Comment