What Are We Doing in This Post?
So far every piece of code we wrote ran from top to bottom, once. If you needed the same logic in two places, you had to write it twice.
Functions fix this. A function is a named block of code that you define once and call as many times as you need, from anywhere in your file. This is one of the most important concepts in all of programming — it is how real applications stay clean, organized, and maintainable.
Defining and Calling a Function
Real world analogy: A function is like a vending machine. You set it up once. Every time someone presses a button, it performs the same action and gives an output. You do not rebuild the machine every time — you just press the button.
<?php
function greet() {
echo "Hello! Welcome to my website.";
}
greet();
greet();
greet();
?>
Output:
Hello! Welcome to my website. Hello! Welcome to my website. Hello! Welcome to my website.
You define a function using the function keyword, then give it a name, then write the code inside curly braces. To run the function, you call it by writing its name followed by parentheses. The same block runs every time you call it.
Functions With Parameters — Sending Data In
A function becomes far more useful when you can pass data into it. The values you pass in are called arguments. The variables that receive them inside the function are called parameters.
<?php
function greet($name) {
echo "Hello, $name! Welcome to my website.";
echo "<br>";
}
greet("Gagan");
greet("Rahul");
greet("Priya");
?>
Output:
Hello, Gagan! Welcome to my website. Hello, Rahul! Welcome to my website. Hello, Priya! Welcome to my website.
The same function, three different outputs — because we passed three different names. The function does not care what name it receives. It just uses whatever comes in.
You can define multiple parameters separated by commas:
<?php
function introduce($name, $city, $job) {
echo "$name is from $city and works as a $job.";
echo "<br>";
}
introduce("Gagan", "Delhi", "Developer");
introduce("Rahul", "Mumbai", "Designer");
?>
Output:
Gagan is from Delhi and works as a Developer. Rahul is from Mumbai and works as a Designer.
Return Values — Getting Data Out
So far our functions just print things. But most of the time you want a function to calculate or process something and give you the result back so you can use it elsewhere. You do this with the return keyword.
<?php
function add($a, $b) {
return $a + $b;
}
$result = add(10, 25);
echo $result;
echo "<br>";
echo add(100, 200);
?>
Output:
35 300
return sends the value back to wherever the function was called. Once return executes, the function stops — no code after return runs.
The returned value can be stored in a variable, echoed directly, or used inside another expression.
<?php
function calculate_total($price, $qty, $tax_rate) {
$subtotal = $price * $qty;
$tax = $subtotal * $tax_rate;
return $subtotal + $tax;
}
$total = calculate_total(999, 3, 0.18);
echo "Total with tax: Rs. $total";
?>
Output:
Total with tax: Rs. 3536.46
Real world use: every e-commerce site has a function exactly like this — it takes a price, quantity, and tax rate and returns the final amount.
Default Parameter Values
Sometimes you want a parameter to have a fallback value in case the caller does not provide one.
<?php
function greet($name, $role = "User") {
echo "Hello, $name! You are logged in as: $role";
echo "<br>";
}
greet("Gagan", "Admin");
greet("Rahul");
?>
Output:
Hello, Gagan! You are logged in as: Admin Hello, Rahul! You are logged in as: User
When greet is called with two arguments, both are used. When called with one argument, $role falls back to its default value "User". Default parameters must always come after non-default ones.
Variable Scope — Where Variables Live
This is one of the most misunderstood topics for beginners so pay close attention.
In PHP, a variable defined outside a function is not automatically available inside that function. And a variable defined inside a function is not available outside it.
<?php
$message = "I am outside the function.";
function test() {
echo $message;
}
test();
?>
Output: nothing — or a warning depending on your PHP settings.
PHP functions have their own separate scope. The variable $message exists in the global scope but the function cannot see it. To use a global variable inside a function, you must explicitly declare it with the global keyword.
<?php
$message = "I am outside the function.";
function test() {
global $message;
echo $message;
}
test();
?>
Output: I am outside the function.
However — in real professional PHP and especially in Laravel, using global variables inside functions is considered bad practice. The clean approach is to pass the value as a parameter instead.
<?php
$message = "I am outside the function.";
function test($msg) {
echo $msg;
}
test($message);
?>
This is cleaner, more predictable, and easier to debug. Always prefer passing values as parameters over using global.
Returning Multiple Values Using an Array
A function can only return one value. But that value can be an array — which means you can effectively return multiple pieces of data.
<?php
function get_user() {
return [
"name" => "Gagan",
"email" => "gagan@gmail.com",
"role" => "Admin"
];
}
$user = get_user();
echo $user["name"];
echo "<br>";
echo $user["email"];
echo "<br>";
echo $user["role"];
?>
Output:
Gagan gagan@gmail.com Admin
This pattern is used constantly in Laravel — service functions and repository functions return arrays or objects with multiple fields.
A Real World Example — Invoice Generator
Let us put everything together. A clean invoice generator using multiple functions.
Create invoice.php in your phplearning folder:
<!DOCTYPE html>
<html>
<head>
<title>Invoice</title>
</head>
<body>
<?php
function calculate_subtotal($price, $qty) {
return $price * $qty;
}
function apply_discount($amount, $discount_percent) {
return $amount - ($amount * $discount_percent / 100);
}
function apply_tax($amount, $tax_percent = 18) {
return $amount + ($amount * $tax_percent / 100);
}
function format_price($amount) {
return "Rs. " . number_format($amount, 2);
}
$items = [
["name" => "Laptop Stand", "price" => 1299, "qty" => 1],
["name" => "USB Hub", "price" => 899, "qty" => 2],
["name" => "Webcam", "price" => 2499, "qty" => 1],
];
$subtotal = 0;
echo "<h2>Invoice</h2>";
echo "<table border='1' cellpadding='8'>";
echo "<tr><th>Item</th><th>Price</th><th>Qty</th><th>Subtotal</th></tr>";
foreach ($items as $item) {
$item_subtotal = calculate_subtotal($item["price"], $item["qty"]);
$subtotal += $item_subtotal;
echo "<tr>";
echo "<td>" . $item["name"] . "</td>";
echo "<td>" . format_price($item["price"]) . "</td>";
echo "<td>" . $item["qty"] . "</td>";
echo "<td>" . format_price($item_subtotal) . "</td>";
echo "</tr>";
}
echo "</table>";
$after_discount = apply_discount($subtotal, 10);
$final_total = apply_tax($after_discount);
echo "<p>Subtotal: " . format_price($subtotal) . "</p>";
echo "<p>After 10% Discount: " . format_price($after_discount) . "</p>";
echo "<p>After 18% GST: " . format_price($final_total) . "</p>";
?>
</body>
</html>
Visit http://localhost:8080/phplearning/invoice.php
You will see a complete invoice with per-item subtotals, a discount applied to the total, GST added on top, and all prices formatted cleanly with two decimal places. Every calculation is in its own function — clean, reusable, and easy to change.
What Did We Learn in This Post?
Functions are named reusable blocks of code defined with the function keyword and called by name with parentheses.
Parameters let you pass data into a function. Multiple parameters are separated by commas.
return sends a value back from the function to the caller. Once return executes, the function stops.
Default parameter values provide fallbacks when an argument is not passed.
PHP functions have their own scope. Variables outside a function are not visible inside it unless passed as parameters or declared with global. Always prefer parameters.
A function can return an array to effectively send back multiple values at once.
What is Coming in Episode 09?
Next we cover forms and user input — how PHP receives data that a user types into a form on a webpage.
This is where PHP stops being theoretical and becomes genuinely interactive. A user fills out a form, clicks submit, and PHP processes whatever they typed. Episode 09 covers GET and POST methods, the $_GET and $_POST superglobals, basic input validation, and a complete working contact form.
See you in the next one.
Next Episode: Forms and User Input — Making PHP Interactive
This is Episode 08 of the PHP and Laravel — Zero to Hero series.
No comments:
Post a Comment