Wednesday, 17 January 2018

Functions In PHP

Function is a Self-contained block of statement.
There are two types of function such as
1) User defined function
2) Predefined function

Advantages:
Code Reusability
Less Code: Less code is required in php because you don’t need to write the code again and again. It saves code

User defined Functions
The function which is defined by user is called User defined function.

Function definition

function functionname()
{  
//Statement
}  
Function Call
functionname();

Example 1( Using No parameter)

demo.php

<?php  

function display()    //function definition
{  
echo "HI, welcome to LearningPoint92";  
}  

display ();      //function  call 
?>  
Output:

HI, welcome to LearningPoint92

Example 2( Using parameter)

  demo.php
   <?php
   function display($name, $age)
      {
                echo "Name = $name";
                echo "Age = $age</br>";
        }

        display("Dhananjay", 7);
        ?>
Output:
Name= Dhananjay
Age=7

Return Statement

<?php
  
function add($a,$b){  
return $a+$b;  
}  

echo "Addition is: ".add(3,4);  
?>  
Output:
Addition is: 7

Default Argument

Default argument is an argument which will take the default value if you don't specify any argument at the time of function call.

    demo.php

     <?php
      function display($name="Shashank", $age=34)
        {
        echo  "Name = $name";
        echo " Age = $age</br>";
        }
         display("Dhananjay", 7);
         display("dev");
         display();
        ?>
Output:
Name = Dhananjay Age = 7
Name = dev Age = 34
Name = Shashank Age = 34

Call by Value 

Original value cannot be changed after function call.

Value passed to the function is called as call by value.

demo.php

<?php

function ref1($str1)
{
$str1.= ' Using Call by Value'; //$str1=$str1.Using Call by Value      
}

$str2="Hello Shashank";

echo "Before function call : $str2</br>";

ref1($str2);

echo "After function call : $str2";
?>

Output:

Before function call : Hello Shashank
After function call : Hello Shashank

Call by Reference

Original value can be changed after function call

We need to use ampersand (&) symbol before the argument name to pass value as a reference

demo.php

<?php

function ref1(&$str1)
{
$str1. = ' Using Call by reference';  //$str1=$str1.Using Call by reference
}

$str2="Hello Shashank";

echo "Before function call: $str2</br>";

ref1($str2);

echo "After function call : $str2";
?>
Output: 

Before function call: Hello Shashank
After function call: Hello Shashank Using Call by reference


1 comment:

  1. Nice explanation for Call by Value and Call by reference. Cheers!

    ReplyDelete

apply function in R

1) apply function: It takes 3 arguments matrix,margin and function.. Example: m<-matrix(c(1,2,3,4),nrow=2,ncol=2) m #1 indicates it is ap...