PHP Function
A function in PHP is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reuse.
PHP supports a structured programming approach by arranging the processing logic by defining blocks of independent reusable functions. The main advantage of this approach is that the code becomes easy to follow, develop and maintain.
Creating a Function
While creating a user defined function we need to keep few things in mind:
- Any name ending with an open and closed parenthesis is a function.
- A function name always begins with the keyword function.
- To call a function we just need to write its name followed by the parenthesis
- A function name cannot start with a number. It can start with an alphabet or underscore.
- A function name is not case-sensitive
// define a function called `sum` that will // receive a list of numbers as an argument. function sum($numbers) { // initialize the variable we will return $sum = 0; // sum up the numbers foreach ($numbers as $number) { $sum += $number; } // return the sum to the user return $sum; } // Example usage of sum echo sum([1,2,3,4,5,6,7,8,9,10]);
PHP Function Arguments
We can pass the information in PHP function through arguments which is separated by comma.
PHP supports Call by Value (default), Call by Reference, Default argument values and Variable-length argument list.
PHP Return Type Declarations
<?php declare(strict_types=1); // strict requirement function addNumbers(float $a, float $b) : float { return $a + $b; } echo addNumbers(1.2, 5.2); ?>