Default Parameters, Named Arguments & Variable Scope
Master PHP default parameters, named arguments (PHP 8+), local and global scope, the global keyword, and $GLOBALS for professional function design.
Default Parameters, Named Arguments & Variable Scope
Introduction
In the previous lesson, you learned how to create functions, pass parameters, and return values.
However, professional PHP applications require much more than basic functions.
Imagine you're building an e-commerce platform.
Your application needs to:
- Calculate taxes with different tax rates.
- Send emails with optional parameters.
- Generate invoices in different currencies.
- Track how many times a function has been called.
- Share configuration values across multiple functions.
PHP provides advanced function features that make these tasks simple, clean, and maintainable.
In this lesson, you'll learn:
- Default Parameter Values
- Named Arguments (PHP 8+)
- Variable Scope
- Local Variables
- Global Variables
- The global Keyword
- The $GLOBALS Array
These concepts are used daily in Laravel, Symfony, CodeIgniter, WordPress, and enterprise PHP applications.
Default Parameter Values
Sometimes a function parameter has a value that is commonly used.
Instead of forcing every caller to pass that value, PHP allows you to define a default value.
If no argument is provided, PHP automatically uses the default.
Syntax
function functionName($parameter = defaultValue){// Code}
Example 1: Greeting Users
<?phpfunction greet($name = "Guest"){echo "Welcome, " . $name;}greet();
Output:
Welcome, Guest
Passing a value overrides the default.
greet("Rahul");
Output:
Welcome, Rahul
Why Default Parameters Are Useful
Imagine an online shopping website.
Most orders use the Indian Rupee (INR).
Instead of specifying the currency every time, you can define it once.
function displayPrice($price, $currency = "INR"){echo $currency . " " . $price;}displayPrice(1500);
Output:
INR 1500
Another example:
displayPrice(1500, "USD");
Output:
USD 1500
Multiple Default Parameters
function createUser($name = "Guest", $role = "User"){echo $name . " - " . $role;}createUser();
Output:
Guest - User
Calling the function with values:
createUser("John", "Admin");
Output:
John - Admin
Rules for Default Parameters
Default parameters must always come after required parameters.
Correct:
function calculateTax($price, $tax = 18){}
Incorrect:
function calculateTax($tax = 18, $price){}
PHP does not allow optional parameters before required ones.
Real-World Example: Shipping Charges
<?phpfunction calculateShipping($weight, $chargePerKg = 50){return $weight * $chargePerKg;}echo calculateShipping(4);
Output:
200
Express shipping:
echo calculateShipping(4, 120);
Output:
480
Named Arguments (PHP 8+)
Before PHP 8, arguments had to be passed in the exact order defined by the function.
PHP 8 introduced Named Arguments.
Named arguments let you specify the parameter name when calling a function.
This improves readability and allows you to skip optional parameters.
Example
function registerUser($name, $email, $role = "User"){echo "$name - $email - $role";}registerUser(name: "Rahul",email: "rahul@example.com");
Output:
Rahul - rahul@example.com - User
PHP automatically assigns values based on the parameter names.
Changing the Order
Named arguments allow parameters to appear in a different order.
registerUser(email: "john@example.com",name: "John",role: "Admin");
Output:
John - john@example.com - Admin
Without named arguments, this would produce incorrect results.
Benefits of Named Arguments
- Improves readability.
- Makes function calls self-documenting.
- Reduces mistakes when many optional parameters exist.
- Lets you skip optional arguments.
Named arguments are especially useful when working with framework APIs and library functions that accept many parameters.
Variable Scope
A variable's scope determines where it can be accessed.
Understanding scope helps you avoid bugs and write predictable code.
PHP provides several types of scope:
- Local Scope
- Global Scope
- Static Scope
In this lesson, we'll begin with local and global scope.
Local Scope
A variable declared inside a function exists only inside that function.
Example:
<?phpfunction showMessage(){$message = "Hello PHP";echo $message;}showMessage();
Output:
Hello PHP
Outside the function:
echo $message;
Result:
Undefined variable
The variable belongs only to the function.
Why Local Scope Matters
Imagine two developers writing functions.
Developer A:
function calculateSalary(){$total = 50000;}
Developer B:
function calculateBonus(){$total = 5000;}
Both functions use the variable $total.
There is no conflict because each function has its own local scope. This isolation prevents accidental interference between different parts of the program.
Global Scope
Variables declared outside functions belong to the global scope.
Example:
<?php$company = "TechLearningPro";
This variable exists in the global scope.
However, it cannot be accessed directly inside a function.
Example:
<?php$company = "TechLearningPro";function displayCompany(){echo $company;}displayCompany();
Output:
Undefined variable
The global Keyword
To use a global variable inside a function, use the global keyword.
Example:
<?php$company = "TechLearningPro";function displayCompany(){global $company;echo $company;}displayCompany();
Output:
TechLearningPro
The global keyword tells PHP to use the variable from the global scope.
Multiple Global Variables
<?php$tax = 18;$currency = "INR";function showSettings(){global $tax, $currency;echo $tax . "% " . $currency;}showSettings();
Output:
18% INR
The $GLOBALS Superglobal
PHP also provides a special associative array called $GLOBALS.
It contains every global variable.
Example:
<?php$company = "TechLearningPro";function displayCompany(){echo $GLOBALS["company"];}displayCompany();
Output:
TechLearningPro
This works without using the global keyword.
Modifying Global Variables
You can also change global values.
<?php$count = 10;function increase(){$GLOBALS["count"]++;}increase();echo $count;
Output:
11
Real-World Example: Website Configuration
<?php$siteName = "TechLearningPro";$version = "2.1";function displayFooter(){global $siteName, $version;echo $siteName . " v" . $version;}displayFooter();
Output:
TechLearningPro v2.1
Real-World Example: Tax Calculation
<?php$defaultTax = 18;function calculateGST($price){global $defaultTax;return $price + ($price * $defaultTax / 100);}echo calculateGST(1000);
Output:
1180
Should You Use Global Variables?
Although PHP supports global variables, professional developers use them carefully.
Why?
Because global variables:
- Can be modified from many places.
- Make debugging more difficult.
- Increase coupling between different parts of the application.
- Reduce code reusability.
Modern PHP applications usually pass values as parameters instead of relying on global variables.
Frameworks like Laravel encourage dependency injection and service containers instead of extensive global state.
Best Practices
Prefer Parameters Over Globals
Instead of:
global $tax;
Prefer:
calculateGST($price, $tax);
This makes the function reusable and easier to test.
Use Meaningful Parameter Names
Bad:
function test($x)
Better:
function calculateSalary($monthlySalary)
Descriptive names improve readability.
Keep Variables Local Whenever Possible
Local variables reduce side effects and prevent accidental modifications.
Use Default Values for Optional Parameters
If a parameter usually has the same value, define a sensible default instead of requiring callers to pass it every time.
Use Named Arguments for Readability
Named arguments make long function calls much easier to understand, especially when multiple optional parameters are involved.
Common Mistakes
Forgetting Required Parameters
function add($a, $b){}
Calling:
add(10);
results in an error because the second required parameter is missing.
Placing Optional Parameters Before Required Ones
Incorrect:
function test($tax = 18, $price){}
Always place required parameters first.
Assuming Global Variables Are Automatically Available
Variables declared outside a function are not automatically visible inside it. Use global, $GLOBALS, or—better—pass them as parameters.
Overusing Global Variables
Using too many global variables makes applications difficult to understand and maintain. Favor local variables and function parameters.
Hands-on Exercise
Create a PHP program that:
- Creates a function with a default greeting message.
- Calculates shipping cost using a default shipping rate.
- Uses named arguments to register a user.
- Demonstrates local scope with two different functions.
- Uses the global keyword to display a company name.
- Updates a global counter using $GLOBALS.
- Refactors one function to remove its dependency on global variables by passing the value as a parameter.
Try implementing each example yourself before comparing it with the solutions.
Summary
Advanced function features make your PHP code cleaner, more flexible, and easier to maintain.
Default parameters reduce repetitive code, named arguments improve readability, and understanding variable scope helps you avoid unexpected bugs.
Although PHP allows global variables, professional developers generally prefer passing data through function parameters because it produces more predictable, testable, and reusable code.
Key Takeaways
- Default parameters provide fallback values for optional arguments.
- Required parameters must come before optional parameters.
- Named arguments (PHP 8+) improve readability and flexibility.
- Local variables exist only within the function where they are declared.
- Global variables are defined outside functions.
- Use the global keyword or $GLOBALS to access global variables inside functions.
- Prefer passing values as parameters instead of relying on global variables.
- Understanding variable scope is essential for writing maintainable PHP applications.
What's Next?
In Static Variables, Variadic Functions & Argument Unpacking, you'll learn how functions remember state, accept any number of arguments, and unpack arrays into parameters.
Continue at /learn/php/functions-part-2b-1.