PHP default argument values

If you don’t pass any value to the function, it will use default argument value.
PHP default argument values is an example of passing arguments to function.

For example:

Output:

In above example, we don’t pass any value to function family().
But when it is call it will use default value.
As shown in first family() function call, it take 5 as value for $members.
But in second family() function call, it use value of $members is 2 because it is pass by function.

 

PHP allows the use of special type NULL as default values.

For example:

Output:

 

Output:

Also PHP allows use of arrays as default values.
You can not use a variable, a class member or a function call as default value.
The default value must be a constant expression.

If you are going to use one default argument and another is non-default argument.
Then make sure any defaults should be on the right side of any non-default arguments.
Otherwise, things will not work as expected.

For example:

Output:

This above example won’t work as expected. Therefore the correct code is shown in below example:

 

Ankit Wasankar

Senior Java Developer
Java 11 | Microservices | Reactjs | SQL

Help others by sharing the content!

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.