Fork me on GitHub

Functions


Reasons


Features

1
2
<?php
function name() { }
1
2
3
4
5
6
7
8
9
10
<?php
function printList($string, $count = 5)

function newTo5(&$number = 2)

$a = func_get_args();

int func_num_args(void)

mixed func_get_arg ( int $arg_num )

By reference

http://php.net/manual/en/language.references.return.php

1
2
<?php
function &name() { }

Anonymous Functions, closures

http://php.net/manual/en/functions.anonymous.php

Аllow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class.

1
2
3
4
5
6
7
8
9
<?php
$greet = function($name)
{
    printf("Hello %s\r\n", $name);
};

$greet('World');
$greet('PHP');
?>

It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure.

The predefined final class Closure was introduced in PHP 5.3.0. It is used for internal implementation of anonymous functions. The class has a constructor forbidding the manual creation of the object (issues E_RECOVERABLE_ERROR) and the __invoke method with the calling magic.

May also inherit variables from the parent scope.

1
2
3
4
5
6
7
8
9
10
<?php
$callback =
            function ($quantity, $product) use ($tax, &$total)
            {
                $pricePerItem = constant(__CLASS__ . "::PRICE_" .
                    strtoupper($product));
                $total += ($pricePerItem * $quantity) * ($tax + 1.0);
            };
        
        array_walk($this->products, $callback);
blog comments powered by Disqus