PHP Functions
Learn about functions in PHP and their types.
We'll cover the following
Functions in PHP
Functions are the heart of functional programming. Functions are relationships between inputs and outputs. The arity of a function is the number of arguments a function accepts, and the function signature specifies return types and argument types. Lastly, the definition of a function encapsulates the function logic. Here’s a mathematically defined function:
It has an arity of one, and it increments the value of the parameter by 1. The parameter is effectively a placeholder for a general transformation given in the function definition using the addition operation: . Different results are obtained for different values of because the function offers localized computation. Each result is, therefore, unique to each input. For example:
Functions in PHP take on many forms. They’re just as flexible as variables and have the following characteristics:
-
The
function
keyword. -
Two sets of parentheses:
- Round brackets
()
for the arguments. - Curly braces
{}
for the function definition.
- Round brackets
-
A return type (as of PHP version 7.0).
Types of functions in PHP
The different types of functions in PHP are the following:
- Named functions
- Anonymous functions
- Closures
- Methods
Named functions
Named functions in PHP, like the one below, are identical (apart from a few syntactic differences) to those defined in other programming languages. They typically have an arbitrary name sandwiched between a function keyword and an argument list followed by the function definition, that contains state transformation expressions.
Get hands-on with 1400+ tech skills courses.