These examples cover a range of advanced PHP features and functions that can enhance your code organization and functionality.
PHP Advanced Functions
Closure
$add = function($a, $b) {
return $a + $b;
};
echo $add(3, 4);
// Outputs 7
- Closures allow you to create anonymous functions, useful for tasks like callback functions.
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
- Generators provide an easy way to implement simple iterators.
Anonymous Classes
$obj = new class {
public function sayHello() {
echo "Hello!";
}
};
$obj->sayHello();
// Outputs: Hello!
- Anonymous classes allow you to create simple, one-off objects without defining a class.
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_map applies a callback function to each element of an array and returns the modified array.
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_filter filters elements of an array using a callback function.
array_reduce
$numbers = [1, 2, 3, 4];
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
echo $sum;
// Outputs: 10
- array_reduce applies a callback function to the elements of an array, reducing it to a single value.
spl_autoload_register
spl_autoload_register(function($class) {
include 'classes/' . $class . '.class.php';
});
- spl_autoload_register allows you to register multiple autoload functions, useful for automatically loading classes.
×