PHP


Functional Programming All Versions

Legacy Versions

1.0
2.0
3.0

PHP 4.x

4.0
4.1
4.2
4.3
4.4

PHP 5.x

5.0
5.1
5.2
5.3
5.4
5.5
5.6

PHP 7.x

7.0
7.1

This draft deletes the entire topic.

Introduction

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. This topic describes the declaration and utilization of functions, arguments, parameters, return statements and scope in PHP.

expand all collapse all

Examples

  • 8

    A closure is an anonymous function that can 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.

    $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 (use()).

    $myFunction = function() use($externalVariable, $secondExternalVariable) {
       var_dump($externalVariable, $secondExternalVariable); // Hello Foo
    }
    

    This is heavily attributed to PHP's tight variable scoping - If a variable isn't defined within the scope, or isn't brought in with global then it does not exist.

    Also note:

    Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing.

    The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

    Taken from the PHP Documentation for Anonymous Functions


    In PHP, closures use an early-binding approach. This means that variables passed to the closure's namespace using use keyword will have the same values when the closure was defined.

    To change this behavior you should pass the variable by-reference.

    $rate = .05;
    
    // Exports variable to closure's scope
    $calculateTax = function ($value) use ($rate) {
        return $value * $rate;
    };
    
    $rate = .1; 
    
    print $calculateTax(100); // 5
    
    $rate = .05;
    
    // Exports variable to closure's scope
    $calculateTax = function ($value) use (&$rate) { // notice the & before $rate
        return $value * $rate;
    };
    
    $rate = .1;
    
    print $calculateTax(100); // 10
    

    Default arguments are not implicitly required when defining anonymous functions with/without closures.

    $message = 'Im yelling at you';
    
    $yell = function() use($message) {
        echo strtoupper($message);
    };
    
    $yell(); // returns: IM YELLING AT YOU
    
  • 5

    Anonymous functions can be assigned to variables for use as parameters where a callback is expected:

    $uppercase = function($data) {
        return strtoupper($data);
    };
    
    $mixedCase = ["Hello", "World"];
    $uppercased = array_map($uppercase, $mixedCase);
    print_r($uppercased);
    

    These variables can also be used as standalone function calls:

    echo $uppercase("Hello world!"); // HELLO WORLD!
    
  • 2

    An anonymous function is just a function that doesn't have a name.

    // Anonymous function
    function() {
        return "Hello World!";
    };
    

    In PHP, an anonymous function is treated like an expression and for this reason, it should be ended with a semicolon ;.

    An anonymous function should be assigned to a variable.

    // Anonymous function assigned to a variable
    $sayHello = function($name) {
        return "Hello $name!";
    };
    
    print $sayHello('John'); // Hello John
    

    Or it should be passed as parameter of another function.

    $users = [
        ['name' => 'Alice', 'age' => 20], 
        ['name' => 'Bobby', 'age' => 22], 
        ['name' => 'Carol', 'age' => 17]
    ];
    
    // Map function applying anonymous function
    $userName = array_map(function($user) {
        return $user['name'];
    }, $users);
    
    print_r($usersName); // ['Alice', 'Bobby', 'Carol']
    

    Or even been returned from another function.

Please consider making a request to improve this example.

Syntax

Syntax

Parameters

Parameters

Remarks

Remarks

Still have a question about Functional Programming? Ask Question

Topic Outline