start learning
Image 1
5FunctionsPHP

PHP Advanced Functions

These examples cover a range of advanced PHP features and functions that can enhance your code organization and functionality.


Closure

$add = function($a, $b) {
    return $a + $b;
};
echo $add(3, 4); 
// Outputs 7

Generator

function generateNumbers($start, $end) {
    for ($i = $start; $i <= $end; $i++) {
        yield $i;
    }
}

foreach (generateNumbers(1, 5) as $number) {
    echo $number . ' ';
}
// Outputs: 1 2 3 4 5

Anonymous Classes

$obj = new class {
    public function sayHello() {
        echo "Hello!";
    }
};

$obj->sayHello(); 
// Outputs: Hello!

array_map

$numbers = [1, 2, 3, 4];

$squared = array_map(function($n) {
    return $n * $n;
}, $numbers);

print_r($squared); // Outputs: Array ( [0] => 1 [1] => 4 [2] => 9 [3] => 16 )

array_filter

$numbers = [1, 2, 3, 4, 5];

$evenNumbers = array_filter($numbers, function($n) {
    return $n % 2 == 0;
});

print_r($evenNumbers); 
// Outputs: Array ( [1] => 2 [3] => 4 )

array_reduce

$numbers = [1, 2, 3, 4];

$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);

echo $sum; 
// Outputs: 10

spl_autoload_register


spl_autoload_register(function($class) {
    include 'classes/' . $class . '.class.php';
});

×