What are the types of functions in PHP?
Overview
A function is a piece of code used to perform a specific operation or task. It provides better reuse-ability and modularity for the application.
In PHP, it receives the input from the user in the form of arguments and performs particular actions. In some situations, it delivers the output in the form of a return value.
Types of functions in PHP
There are three types of functions in PHP:
- Named functions
- Anonymous functions
- Class methods
Named functions
Named functions are similar to any function given in any other language, except these have some syntactic differences. See an example of the Sum() function below.
<?phpfunction Sum (int $num1, int $num2):int{return $num1+$num2;}echo Sum(5,4)?>
Explanation
- Line 2: We define a
Sum()function with two parameters of integer types$num1and$num2, and return typeint. - Line 4: We return the sum of the provided integers.
- Line 5: We display the sum of two integers,
5and4, returned by theSum()function.
Anonymous functions
Sometimes we need functions for one-time use. For this purpose, anonymous functions are defined without a user-given name and are known as lambda or closure functions. Generally, they are used to create an inline callback function.
Syntax
Let’s have a look at the given syntax of an anonymous function.
$var=function ($arg1, $arg2) { return $val; };
Example
Let’s look at the example code to write an anonymous function.
<?php$Sum = function ($num1,$num2) {return $num1+$num2;};echo "Sum of 3 and 7 is: " . $Sum(3,7);?>
Explanation
- Line 2: We define a function with two parameters of integer types
$num1and$num2, and return the sum of the provided integers. - Line 3: We display the sum of two integers returned by the anonymous function.
Class methods
A class method is a function encapsulated within the scope of a class.
Example
Let’s look at an example of the Sum() method in the Complex class.
<?phpclass Complex{private $real;private $img;public function __construct(float $real, float $img){$this->real=$real;$this->img=$img;}public function Sum(Complex $c2):Complex{return new Complex($this->real+$c2->real, $this->img+$c2->img);}}$first = new Complex(2,4);$second = new Complex(3,5);$sum = $first->Sum($second);var_dump($sum);?>
Explanation
- Lines 4–5: We define the data-members
$realand$imgof theComplexclass. - Lines 6–10: We define a constructor of the
Complexclass. - Lines 11–14: We define a
Sum()method that returns the sum of twoComplexclass objects in a third object. - Lines 16–17: We create the instances of the
Complexclass. - Line 18: We call the
Sum()method of theComplexclass. - Line 19: We print the detail of the return value on screen.
Free Resources