×
☰ See All Chapters

PHP Functions

PHP function is a collection of statements that are grouped together to perform an operation. Functions can take input in the form of parameters, performs the operation on input and returns a result to the caller. A function will be executed by a call to the function.

You may call a function from anywhere within a page.

PHP's functional programming relies on functions. Functions in PHP provide organized, reusable code to perform a set of actions. Functions simplify the coding process, prevent redundant logic, and make code easier to follow.

Create a PHP Function

Function has the following syntax (function definition).

function functionName ($pmtr1, $pmtr2, $pmtr3...) : returnType

{

    //function body

    return exp;|return;

}

functionName

  • Give the function a name that reflects what the function does 

  • The function name can start with a letter or underscore (not a number) 

Parameters

  • ($pmtr1, $pmtr2, $pmtr3...) are the input parameters of a function. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called.  

  • Function can have any number of Parameters, or parameter list can be empty. 

  • You can specify the type of parameters in front of parameters as below: 

        function functionName (type1 $pmtr1, type2 $pmtr2, type3 $pmtr3...) { … }

Function Body

The function body contains a collection of statements that define what the function does.

Return statement

  • Function may or may not return a value. Return statement is optional. 

  • When you have return statement you can have return expression, but finally expression should be evaluated to a value. 

function functionName()

{

    $a = 10;

    $b = 20;

    return $a + $b;

}

In the above code return expression is $a + $b which gets evaluated to 30;

  • You can just have return statement without any return value or expression. 

function   functionName ()

{

    return;

}

  • After return statement there should be no further code, return statement should be the last statement inside a function. 

Return Type

  • Function can specify the type of the return value. This is optional. If return type is specified then function should have return statement and should return a value of return type. 

  • Return type can be specified as void, In this case function should not have return statement. If return statement is added with void as return type, then it gives fatal error. 

function   functionName () : void

{

    return; //Fatal Error

}

  • PHP supports below list of types for return type: 

php-functions-0
 

Calling a PHP Function

Function can be called with the following syntax.

variable = functionName(arg1, arg2, arg3…)

Function may be/may not be returning a value, accepting the value while calling a function is optional. We can ignore the return value from function call.

If function is not returning a value then syntax to call the function should be:

methodName(arg1, arg2, arg3…)

Arguments arg1, arg2, arg3 are passed to parameters $pmtr1, $pmtr2 and $pmtr3 respectively. If type of parameters is specified in function definition then type of the arguments should match with the type of the parameter in order. Type of argument arg1 should match with the type of parameter pmtr1. Type of argument arg2 should match with the type of parameter pmtr2. Type of argument arg3 should match with the type of parameter pmtr3 So on…

Function Example

<?php

function printHello () {

    echo "Hello </br>";

}

function add($x, $y)

{

    $total = $x + $y;

    return $total;

}

 

printHello();

echo "10 + 20 = " . add(10, 20);

?>

php-functions-1
 

Variable-length argument lists

  • PHP 5.6 introduced variable-length argument lists (also known as varargs, variadic arguments), using the ... token before the argument name to indicate that the parameter is variadic, i.e. it is an array including all supplied parameters from that one onward. 

Function with varargs  has the following syntax.

function functionName ($pmtr1, $pmtr2, ...$pmtr3)

{

    //function body

    return exp;|return;

}

  • Only one variadic is allowed. 

  • Variadic parameter should be the last parameter. 

<?php

 

function variadic_func($nonVariadic, ...$variadic) {

    foreach($variadic as $a) {

        echo $a. "</br>";

    }

}

variadic_func(1, 2, 3, 4); // prints [2,3,4]

?>

In the above example value 1 is passed to $nonVariadic parameter and 2, 3, 4 are passed to  $variadic parameter. Below is the output.

php-functions-2
 

Optional Parameters

You can specify the default value for a parameter; in this case parameter becomes optional for function call.

<?php

 

function add($x, $y=10)

{

    $total = $x + $y;

    return $total;

}

echo "10 + 20 = " . add(10, 20) ."</br>" ;

echo "10 + default value = " . add(10);

?>

php-functions-3
 

Call By Reference

Function arguments can be passed "By Reference", allowing the function to modify the variable used outside the function. In case of PHP call by reference, actual value is modified if it is modified inside the function. In such case, you need to use & (ampersand) symbol with formal arguments.  The & represents reference of the variable. Let's understand the concept of call by reference by the help of example.

<?php

function callByReference(&$str_parameter1)

{

    $str_parameter1 .= 'Call By Reference </br>';

}

$str_arg1 = 'This is ';

callByReference($str_arg1);

echo $str_arg1;

 

function nonCallByReference($str_parameter2)

{

    $str_parameter2 .= 'Non Call By Reference';

}

 

$str_arg2 = 'This is ';

nonCallByReference($str_arg2);

echo $str_arg2;

 

?>  

php-functions-4
 

Anonymous functions

Whenever you have to execute a function only one time, the you can create a anonymous function.  An anonymous function is just a function that doesn't have a name. In PHP, an anonymous function is treated like an expression and for this reason, it should be ended with a Semicolon (;).

// Anonymous function

function() {

    return "Hello World!";

};

As the anonymous functions don’t have name, to call or to execute anonymous functions, you have to assign anonymous function to a variable Or it should be passed as parameter of another function Or even been returned from another function.

<?php

// Anonymous function assigned to a variable

$sayHello = function ($name) {

    return "Hello $name!";

};

print $sayHello('Manu Manjunatha'); // Hello Manu Manjunatha

$users = [

    [

        'name' => 'Manu',

        'age' => 20

    ],

    [

        'name' => 'Advith',

        'age' => 22

    ],

    [

        'name' => 'Manjunatha',

        'age' => 17

    ]

];

// Map function applying anonymous function

$userName = array_map(function ($user) {

    return $user['name'];

}, $users);

?>  

Self-executing anonymous functions

<?php

(function () {

    echo "Hello world!";

})();

 

// For PHP 7.x

(function ($name) {

    echo "Hello $name!";

})('Manu Manjunatha');

 

?>  

 

Closures

Closure is an anonymous function that can't access outside scope. When defining an anonymous function as such, you're creating a "namespace" for that function. It currently only has access to that namespace.

<?php

$externalVariable = "Hello";

$secondExternalVariable = "Foo";

$myFunction = function() {

    var_dump($externalVariable, $secondExternalVariable); // returns two error notice, since the variables aren´t defined

}

 

?>  

 

It doesn't have access to any external variables. To grant this permission for this namespace to access external variables, you need to introduce it via closures using use keyword.

<?php

 

$externalVariable = "Hello";

$secondExternalVariable = "Foo";

 

$myFunction = function() use($externalVariable, $secondExternalVariable) {

    var_dump($externalVariable, $secondExternalVariable); // Hello Foo

}

 

?>  


All Chapters
Author