- Php default argument null
- Variable-length argument lists
- . in PHP 5.6+
- Older versions of PHP
- Optional Arguments in PHP
- Use «NULL» as an Optional Argument
- Use a Specific Value as an Optional Argument
- Use an Empty String as an Optional Argument
- Use the Splat Operator ( . ) to Define Optional Argument
- Use func_get_args Method to Set an Optional Argument in PHP
- PHP Default Parameters
- Introduction to the PHP default parameters
- Default arguments
- The order of default parameters
- Summary
Php default argument null
By default, PHP will coerce values of the wrong type into the expected scalar type if possible. For example, a function that is given an integer for a parameter that expects a string will get a variable of type string .
It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown. The only exception to this rule is that an integer may be given to a function expecting a float . Function calls from within internal functions will not be affected by the strict_types declaration.
To enable strict mode, the declare statement is used with the strict_types declaration:
Enabling strict mode will also affect return type declarations.
Note:
Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller’s preference (weak typing) will be respected, and the value will be coerced.
Note:
Strict typing is only defined for scalar type declarations, and as such, requires PHP 7.0.0 or later, as scalar type declarations were added in that version.
Example #11 Strict typing
function sum ( int $a , int $b ) return $a + $b ;
>
var_dump ( sum ( 1 , 2 ));
var_dump ( sum ( 1.5 , 2.5 ));
?>
The above example will output:
int(3) Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 9 and defined in -:4 Stack trace: #0 -(9): sum(1.5, 2.5) #1 thrown in - on line 4
Example #12 Weak typing
function sum ( int $a , int $b ) return $a + $b ;
>
?php
// These will be coerced to integers: note the output below!
var_dump ( sum ( 1.5 , 2.5 ));
?>
The above example will output:
Example #13 Catching TypeError
function sum ( int $a , int $b ) return $a + $b ;
>
try var_dump ( sum ( 1 , 2 ));
var_dump ( sum ( 1.5 , 2.5 ));
> catch ( TypeError $e ) echo ‘Error: ‘ . $e -> getMessage ();
>
?>
The above example will output:
int(3) Error: Argument 1 passed to sum() must be of the type integer, float given, called in - on line 10
Variable-length argument lists
PHP has support for variable-length argument lists in user-defined functions. This is implemented using the . token in PHP 5.6 and later, and using the func_num_args() , func_get_arg() , and func_get_args() functions in PHP 5.5 and earlier.
. in PHP 5.6+
In PHP 5.6 and later, argument lists may include the . token to denote that the function accepts a variable number of arguments. The arguments will be passed into the given variable as an array; for example:
Example #14 Using . to access variable arguments
function sum (. $numbers ) $acc = 0 ;
foreach ( $numbers as $n ) $acc += $n ;
>
return $acc ;
>
?php
The above example will output:
You can also use . when calling functions to unpack an array or Traversable variable or literal into the argument list:
Example #15 Using . to provide arguments
The above example will output:
You may specify normal positional arguments before the . token. In this case, only the trailing arguments that don’t match a positional argument will be added to the array generated by . .
It is also possible to add a type hint before the . token. If this is present, then all arguments captured by . must be objects of the hinted class.
Example #16 Type hinted variable arguments
function total_intervals ( $unit , DateInterval . $intervals ) $time = 0 ;
foreach ( $intervals as $interval ) $time += $interval -> $unit ;
>
return $time ;
>
?php
$a = new DateInterval ( ‘P1D’ );
$b = new DateInterval ( ‘P2D’ );
echo total_intervals ( ‘d’ , $a , $b ). ‘ days’ ;
// This will fail, since null isn’t a DateInterval object.
echo total_intervals ( ‘d’ , null );
?>
The above example will output:
3 days Catchable fatal error: Argument 2 passed to total_intervals() must be an instance of DateInterval, null given, called in - on line 14 and defined in - on line 2
Finally, you may also pass variable arguments by reference by prefixing the . with an ampersand ( & ).
Older versions of PHP
No special syntax is required to note that a function is variadic; however access to the function’s arguments must use func_num_args() , func_get_arg() and func_get_args() .
The first example above would be implemented as follows in PHP 5.5 and earlier:
Example #17 Accessing variable arguments in PHP 5.5 and earlier
function sum () $acc = 0 ;
foreach ( func_get_args () as $n ) $acc += $n ;
>
return $acc ;
>
?php
The above example will output:
Optional Arguments in PHP
- Use «NULL» as an Optional Argument
- Use a Specific Value as an Optional Argument
- Use an Empty String as an Optional Argument
- Use the Splat Operator ( . ) to Define Optional Argument
- Use func_get_args Method to Set an Optional Argument in PHP
In PHP, optional arguments do not prevent the method from working even if no data is given. The article below shows examples of different ways of implementing optional arguments.
Use «NULL» as an Optional Argument
We will create a function and pass a default argument with its value set as «null» . If we call the function without resetting the default argument value, then «null» will be used in its place.
php function fruits($bestfruit = "NULL") return "I love enjoying $bestfruit" .'
'; > echo fruits(); echo fruits('mango'); ?>
I love enjoying NULL I love enjoying mango
Use a Specific Value as an Optional Argument
We will create a function and pass a default argument with its value set as a string. If we call the function without resetting the default argument value, then the specified value will be used in its place.
php function fruits($bestfruit = "Apple") return "I love enjoying $bestfruit" .'
'; > echo fruits(); echo fruits('mango'); ?>
I love enjoying Apple I love enjoying mango
Use an Empty String as an Optional Argument
Create a function and pass a default argument with its value set as an empty string.
php function fruits($bestfruit = "") return "I love enjoying $bestfruit" .'
'; > echo fruits(); echo fruits('PineApples'); ?>
I love enjoying I love enjoying PineApples
Use the Splat Operator ( . ) to Define Optional Argument
Here we don’t pass any default value. Instead, we will pass the splat operator ( . ) that will default define an empty array when no argument has been passed to the function.
php function fruits(. $bestfruit) var_dump($bestfruit).'
'; > echo fruits(); echo fruits('PineApples','test'); ?>
array(0) < >array(2) < [0]=>string(10) "PineApples" [1]=> string(4) "test" >
Use func_get_args Method to Set an Optional Argument in PHP
Same in using the splat operator ( . ), we create a function without passing any default value. If we call the function without specifying a value, 0 will be the default value.
php function summation() $numbers = func_get_args(); return array_sum($numbers); > echo summation().'
'; echo summation(1,2,3,4,5,6); ?>
PHP Default Parameters
Summary: in this tutorial, you’ll learn about PHP default parameters and default parameters to simplify the function calls.
Introduction to the PHP default parameters
The following defines the concat() function that concatenates two strings with a delimiter:
function concat($str1, $str2, $delimiter) < return $str1 . $delimiter . $str2; >
Code language: HTML, XML (xml)
When you call the concat() function, you need to pass exactly three arguments. For example:
function concat($str1, $str2, $delimiter) < return $str1 . $delimiter . $str2; > $message = concat('Hi', 'there!', ' '); echo $message;
Code language: HTML, XML (xml)
However, you’ll find that you often use the space ‘ ‘ as the delimiter. And it’s repetitive to pass the space whenever you call the function.
This is why default parameters come into play.
PHP allows you to specify a default argument for a parameter. For example:
function concat($str1, $str2, $delimiter = ' ') < return $str1 . $delimiter . $str2; >
Code language: HTML, XML (xml)
In this example, the $delimiter parameter takes the space as the default argument.
When you call the concat() function and don’t pass the delimiter argument, the function will use the space for the $delimiter like this:
function concat($str1, $str2, $delimiter = ' ') < return $str1 . $delimiter . $str2; > $message = concat('Hi', 'there!'); echo $message;
Code language: HTML, XML (xml)
However, if you pass an argument for the $delimiter , the function will use that argument instead:
function concat($str1, $str2, $delimiter = ' ') < return $str1 . $delimiter . $str2; > $message = concat('Hi', 'there!', ','); echo $message;
Code language: HTML, XML (xml)
In this example, we passed a comma to the $delimiter . The concat() function used the comma ( , ) instead of the default argument.
When you specify a default argument for a parameter, the parameter becomes optional. It means that you can pass a value or skip it.
Default arguments
The default arguments must be constant expressions. They cannot be variables or function calls.
PHP allows you to use a scalar value, an array, and null as the default arguments.
The order of default parameters
When you use default parameters, it’s a good practice to place them after the parameters that don’t have default values. Otherwise, you will get unexpected behavior. For example:
function concat($delimiter = ' ', $str1, $str2) < return $str1 . $delimiter . $str2; > $message = concat('Hi', 'there!', ','); echo $message;
Code language: HTML, XML (xml)
Summary
- Use default parameters to simplify the function calls.
- Default parameters are optional.