This section provides a tutorial example on how to provide default values to argument variables.
PHP also allows us to provide default values to argument variables using the following syntax
on the function definition statement:
function function_name($arg_1, $arg_2, ... $arg_n=exp) {
...
}
where argument variable, $arg_n, has been assigned with a default value, evaluated from the specified expression, "exp".
Assigning default values to argument variables has several simple rules:
Only scalar values and arrays can be used as argument variable default values.
Objects can not be used as argument variable default values.
If argument variable has default value defined, the function call operation use that default value by skipping
that argument.
To help us understand how use argument variable default values, I wrote this tutorial example:
<?php # ArgumentDefaultValues.php
# Copyright (c) 2003 by Dr. Herong Yang. http://www.herongyang.com/
#
function hello($name="Herong") {
print(" Hello " . $name . "!\n");
}
print("\n Argument with a scalar default value:\n");
hello();
hello("World");
hello(NULL);
function showList($list=array("Apple", "Orange")) {
print(" List: " . $list[0] . ", " . $list[1] . "\n");
}
print("\n Argument with an array default value:\n");
showList();
showList(array("Cat", "Dog"));
# function showDate($object=new DateTime()) {
# print(" Year: " . $object->format("Y"));
# }
?>
If you run this sample script, you should get:
Argument with a scalar default value:
Hello Herong!
Hello World!
Hello !
Argument with an array default value:
List: Apple, Orange
List: Cat, Dog
If you open last 3 commented-out statements, you will get an execution error:
"Parse error: syntax error, unexpected T_NEW in C:\herong\php\ArgumentDefaultValues.php on line 21",