📡 You're offline — showing cached content
New version available!
Quick Access
PHP Beginner

PHP Functions: Write Once, Use Everywhere

Learn PHP functions — parameters, return values, default parameters, and variable scope.

EzyCoders Admin April 17, 2026 2 min read 0 views
PHP Functions: Write Once, Use Everywhere
Share: Twitter LinkedIn WhatsApp

What is it?

A function is a named, reusable block of code. You define it once and call it as many times as needed from anywhere in your application.

Why does it matter?

Functions prevent code duplication. Without them you would copy-paste the same logic everywhere — one bug fix would require updating dozens of places.

Learn PHP functions — parameters, return values, default parameters, and variable scope.

Real-World Use Cases

  • ✉️ Email sending - Wrap smtp logic in a sendEmail() function — call it from registration, password reset, and order confirmation in one line each.
  • 🔒 Password hashing - A hashPassword() function ensures every part of your app uses the same secure algorithm consistently.
  • 💰 Price formatting - A formatPrice() function adds the currency symbol and decimal places — change it once, every price display updates.
  • 🧪 Input validation - Group validation rules into validateUser() — reuse on registration form, profile update, and admin panel.

Defining and Calling

<!--?php
function sayHello() {
    echo 'Hello, EzyCoders!';
}
sayHello();  // Hello, EzyCoders!
sayHello();  // call again — no copy-paste needed

Parameters and Return Values

<!--?php
function greet($name) {
    echo "Hello, $name!";
}
greet('Rahul');   // Hello, Rahul!
greet('Priya');   // Hello, Priya!

function add($a, $b) {
    return $a + $b;  // sends result back to caller
}
echo add(5, 3);  // 8

Default Parameter Values

<!--?php
function greet($name, $greeting = 'Hello') {
    echo "$greeting, $name!";
}
greet('Rahul');              // Hello, Rahul!
greet('Priya', 'Welcome');   // Welcome, Priya!

Scope and Type Declarations

<!--?php
$g = 'global';
function test() {
    global $g;   // must declare to access outer variable
    echo $g;     // global
}
test();

// PHP 7+ type declarations
function multiply(int $a, int $b): int {
    return $a * $b;
}
echo multiply(4, 5);  // 20

Q: What is the difference between a parameter and an argument?

A parameter is the variable in the function definition. An argument is the actual value passed when calling. In add($a,$b) — $a and $b are parameters; in add(5,3) — 5 and 3 are arguments.

EzyCoders Admin
Written by
EzyCoders Admin

Team Lead and Full-Stack Developer with experience in PHP, JavaScript, SQL, DSA, and System Design. Passionate about software engineering, scalable web technologies, and helping developers prepare for coding interviews and tech careers through practical tutorials and professional guidance.

Comments (0)

No comments yet. Be the first!

Leave a Comment