Simple Function
Using strict type FunctionSyntax
function functionName() {
code to be executed;
}Example
<?php
function writeMsg() {
echo "Hi Hello NUV!";
}writeMsg(); // call the function
?>
Function with arguments
<?phpfunction familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Koosh");
familyName("Dino");
familyName("Ronaldo");
familyName("Ritz");
familyName("Maria");?>
Working with Default Value<?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
?>
Functions with return value<?php
declare(strict_types=1); // strict requirementfunction setHeight(int $minheight = 50) {
echo "The height is : $minheight <br>";
}setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);?>
Passing arguments by Reference<?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);?>
Parameterized Function<?php
function add_five(&$value) {
$value += 5;
}$num = 2;
add_five($num);
echo $num;?>
<?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);?>