PHP
Default parameter values
Learn to assign a default value to a parameter so it can be skipped at the call.
Default value
You can assign a default value to a parameter. This is the value used when the caller skips that argument. The assignment uses = inside the parentheses.
Example: function greet($name = "Guest") { echo $name; }. The call greet("Alex") prints "Alex"; the call greet() passes no argument, so the default "Guest" is used and "Guest" is printed.
Optional parameter
Parameters with a default are optional: the caller may skip them. This is handy for values that are the same in most calls.
For example in function logMessage($msg, $level = "INFO") { echo "[" . $level . "] " . $msg; } the $level is optional. The call logMessage("Started") skips $level and uses "INFO"; the call logMessage("Error", "ERROR") passes "ERROR" to $level. Optional parameters must always come after required ones.
Exercise Print a log message
Define a function logMessage with parameters $msg and $level = "INFO". In the body write echo "[" . $level . "] " . $msg . "\n";. Then call logMessage("System started") first and logMessage("Connection lost", "ERROR") second.
Show example solution
Define function logMessage($msg, $level = "INFO") { ... }, put echo "[" . $level . "] " . $msg . "\n"; in the body. The first call takes one argument logMessage("System started");, the second takes two logMessage("Connection lost", "ERROR");.
Example solution:
<?php
// Define logMessage and call it twice
function logMessage($msg, $level = "INFO") {
echo "[" . $level . "] " . $msg . "\n";
}
logMessage("System started");
logMessage("Connection lost", "ERROR");
Test yourself
-
Complete the default value
function greet($name____) { echo $name; }
Show answer
function greet($name = "Guest") { echo $name; }
-
What is the output of the following code?
function greet($name = "Guest") {
echo $name;
}
greet();
- $name
- (empty output)
- Guest
- PHP error
Show answer
Guest — Correct. With no argument passed, $name takes its default 'Guest'.
-
Match default value concepts
- Default value
- Used when no argument is passed
- $name = "Guest"
- Default value syntax
- Optional
- A parameter with a default
Next lesson: Multiple parameters