PHP Programming

Hands On No. 13 : Working with user defined function in PHP

Working with user defined function in PHP

Simple Function

Syntax

function functionName() {
code to be executed;
}

Example

<?php

function writeMsg() {
echo "Hi Hello NUV!";
}

writeMsg(); // call the function

?>

Function with arguments

<?php

function familyName($fname) {
echo "$fname Refsnes.<br>";
}

familyName("Koosh");
familyName("Dino");
familyName("Ronaldo");
familyName("Ritz");
familyName("Maria");

?>

Using strict type Function
                              

<?php declare(strict_types=1); // strict requirement


function addNumbers(int $a, int $b) {
return $a + $b;
}
echo addNumbers(5, "5 days");
// since strict is enabled and "5 days" is not an integer, an error will be thrown
?>

Working with Default Value
                              

<?php
declare(strict_types=1); // strict requirement

function setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}

setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);

?>

Functions with return value
                              

<?php

declare(strict_types=1); // strict requirement

function sum(int $x, int $y) {
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);

?>

Passing arguments by Reference
                              

<?php

function add_five(&$value) {
$value += 5;
}

$num = 2;
add_five($num);
echo $num;

?>

Parameterized Function
                              

<?php
//Adding two numbers
function add($x, $y)
{
$sum = $x + $y;
echo "Sum of two numbers is = $sum <br><br>";
}
add(467, 943);

//Subtracting two numbers
function sub($x, $y)
{
$diff = $x -$y;
echo "Difference between two numbers is = $diff";
}
sub(943, 467);

?>