Introduction to PHP – User Defined Functions Part 4

Guest Posts Paolo Nikko Nuñal

In our last part when dealing with PHP functions is that we are going to learn how to return values. This is especially useful for those who are practicing the DRY approach (Don't Repeat Yourself) in programming. A function that returns a value is very effective if you are planning on doing a lot of recursive algorithm. This will also keep your code neat and clean. Here's an example.

<?php
   function Add($x,$y)
   {
       $sum = $x + $y;
       return $sum;
   }

echo Add(10,5);
?>


Based from the example above, when we call the Add() function, it accepts two values $x and $y. We passed the values 10 and 5 respectively and in hand it returns the sum which is 15. Functions that have a return value is important when you are trying to do complex algorithms and you don't need to create other functions that repeat the same thing all over again.

Functions with return statement are also used mostly in getter methods when you are dealing in Object Oriented programming.

<?php
 class Person{


   $name;
   $age;

   public function setName($name){
        $this->name = $name;
   }
   public function setAge($age){
        $this->age = $age;
   }
   public function getName(){
       return $this->name; 
   }
   public function getAge(){
       return $this->age;
   }


 ?>


In our example above, it is the most common type of scenario when you are handling OOP in PHP. When you call the getName and getAge methods, you are actually returning the value of that specific instance of the object. We will talk more about Object Oriented Programming in PHP in later tutorials.