PHP Functions

Creating simple function

 
      <?php
      function display()
      {
          echo "hello its working";
      }
      
      display();
      ?>
    
Output

Passing parameters to functions in php

 
      <?php
//function in php 
function display($input)
{
    echo "Received the value ".$input;
}

$value=2;
display($value);
?>
    
Output

Passing multiple parameters to function

 
      <?php
//function in php 
function display($input1,$input2)
{
    echo "Received the value ".$input1 ." ".$input2;
}

display(3,2);
?>
    
Output

Returning value from a function using return statment

 
      <?php
//function in php 
function display($input1,$input2)
{
    return $input1+$input2;
}

$result = display(3,2);
echo $result;
?>
    
Output

Default parameter for a function in PHP

 
      function display($value=10)
{
    echo $value;
}

display();
?>
    
output 10

Default Paramenter with an argument

 
      <?php
function display($value=10)
{
    echo $value;
}

display(25);
?>
    
Output 25

Enforcing data type strictness for a function in PHP

 
      declare(strict_types=1);
what will be output in this case 
<?php 
function display($input)
{
    echo $input*2;
}

display("satish");
?>
    
output Warning: A non-numeric value encountered in C:\xampp\htdocs\iwp\test.php on line 4

Demo code for enforcing data type strictness in PHP

 
      <?php declare(strict_types=1);
function display(int $input)
{
    echo $input*2;
}

display(3);
?>
    
Output

Making a function accept only a String Datatype as input

 
      <?php declare(strict_types=1);
function display(string $input)
{
    echo $input;
}

display("satish");
?>
    
Output satish

Enforcing a strict datatype return from a function

 
      returning an int instead of a string 
<?php declare(strict_types=1);
function display(string $input):string
{
    return 2;
}

$result = display("Satish");
echo $result;
?>
    
Output Fatal error: Uncaught TypeError: Return value of display() must be of the type string, integer returned in C:\xampp\htdocs\iwp\test.php:4 Stack trace: #0 C:\xampp\htdocs\iwp\test.php(7): display('Satish') #1 {main} thrown in C:\xampp\htdocs\iwp\test.php on line 4

Demo for pass by value to a function

 
      <?php 
function change($input)
{
    $input++;
    echo "value inside the function".$input;
}

$value=2;
change($value);
echo "value after calling the function". $value;
?>
    
Output

Demo code for pass by reference to a function

 
      <?php 
function change(&$input)
{
    $input++;
    echo "value inside the function".$input;
}

$value=2;
change($value);
echo "value after calling the function". $value;
?>
    
Output