Introduction to PHP – User Defined Functions Part 3

Guest Posts Paolo Nikko Nuñal

In our previous tutorial we tackled about how functions work with arguments and how you can pass them variable within them. This time around you are going to learn about how functions work with a default argument value.

Sometimes we call functions without parameters this usually happens if we want a default value already set. If you are using PHP frameworks like CodeIgniter or Cake PHP, you'll often find functions with a default argument value.

Here's an example.

<?php
   function getPerson($name = "John Doe")
   {
       echo $name;
   }

getPerson();
?>


When we call the function getPerson(), we are actually calling it without a variable. You might be confused in the previous tutorial that you need to have a variable passed if the function requires one. If not, the function will return an error. However, it is possible to call a function without passing parameters even though it requires a parameter. This is possible thanks to the default argument value.

From the example above, the getPerson() function is invoke and we call it without passing a value. However, since it already has a default argument value, we don't have to pass a variable. Automatically, when we call the function getPerson() it will return the string "John Doe" since it is the default value of $name.