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.
There are three types of functions in PHP:
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)?>
Sum()
function with two parameters of integer types $num1
and $num2
, and return type int
.5
and 4
, returned by the Sum()
function.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.
Let’s have a look at the given syntax of an anonymous function.
$var=function ($arg1, $arg2) { return $val; };
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);?>
$num1
and $num2
, and return the sum of the provided integers.A class method is a function encapsulated within the scope of a class.
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);?>
$real
and $img
of the Complex
class.Complex
class.Sum()
method that returns the sum of two Complex
class objects in a third object.Complex
class.Sum()
method of the Complex
class.Free Resources