PHP Functions

Learn about functions in PHP and their types.

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:

f(x)=x+1f(x) = x + 1

It has an arity of one, and it increments the value of the parameter xx by 1. The parameter xx is effectively a placeholder for a general transformation given in the function definition using the addition operation: x+1x + 1. Different results are obtained for different values of xx because the function offers localized computation. Each result is, therefore, unique to each input. For example:

f(2)=3f(2) = 3

f(3)=4f(3) = 4

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.
  • 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.