Functions — Built-in & User-defined
Functions group reusable code. Define with function name() { }. Pass parameters and use return to send a value back.
User-defined functions
Functions group reusable code. Define with function name() { }. Pass parameters and use return to send a value back.
Real-life example: A function is a recipe card — write it once, cook the dish whenever you need it.
<?php
function greet(string $name): string {
return "Hello, $name!";
}
echo greet("Asha");
function add(int $a, int $b): int {
return $a + $b;
}
echo add(3, 5); // 8
?>Default parameters and type hints
Parameters can have default values. PHP 7+ supports scalar type hints and return types for safer code.
Real-life example: Default parameters are a coffee shop asking "regular milk?" — you only speak up when you want something different.
<?php
function calculateDiscount(float $price, float $percent = 10): float {
return $price - ($price * $percent / 100);
}
echo calculateDiscount(2000); // 10% default
echo calculateDiscount(2000, 20); // 20%
?>Variable scope
Variables inside a function are local. Use global $name inside a function or pass values as arguments. Avoid global when possible.
Real-life example: Local scope is a private diary in your room. Global is a family notice board everyone can read.
<?php
$site = "Rishtaara";
function showSite(): void {
global $site; // prefer passing as parameter instead
echo $site;
}
showSite();
?>