Introduction to PHP – User Defined Functions Part 2

Guest Posts Paolo Nikko Nuñal

In the last tutorial we managed to create user define PHP functions. This time around, you will be learning on how to pass variables to PHP functions by creating an argument.

Arguments are specified after the function name, are placed inside the parentheses. You can add as many arguments as you want but you need to separate it with a comma. This is essentially important if you are dealing with many functions and passing variables from one function to another.

Here is an example.

<?php
   function getName($name)
   {
      echo "My name is: ".$name;
   }

$name = "John Doe";

getName($name);


From the example above, the function getName has one parameter, we assigned a string into the variable $name and passed that value by calling the getName function and placing the $name inside the function.

<?php
   function getPerson($name,$age)
   {
      echo "My name is: ".$name." I'm ".$age." years old.";
   }

$name = "John Doe";
$age = 24;
getPerson($name,$age);
?>


From the example above, the getPerson function accepts two variables namely name and age. When we call the getPerson function, we also passed two variables the name and age of the person. After which, the function gets invoke and displays the result.

Always remember that when creating a function with arguments, you need to always bear in mind the arguments that it receives and you pass.