19
loading...
This website collects cookies to deliver better user experience
Just the Gist
While the ghost of the past had security issues or lack of support for common programming paradigms, the ghost of the present have seen to that there are quirks and oddities in PHP. As luck would have it, we have mostly addressed the ghost of the past. But today we are visited upon by the ghost of the present, but not all it brings us is of evil.
array_map
and array_filter
let's us transform values and filter them with some handy callback functions. Both of these functions takes two parameters; an array and a callback function to be used on each value in the array. But here's an odd thing: array_map
has a callback as its first parameter, and array_filter
has a callback as its second parameter. <?php
function add5(&$num) {
$num += 5;
}
$a = 10;
add5($a);
echo "December {$a}th";
// Outputs: December 15th
$a
by reference. This means that the variable $a
is actually pointing to the same address as the one being used in the function add5
. So when we call add5
, the value of $a
is being changed. This is what we call pass-by-reference. Similar system is used in C++ too.call_user_func
. Here's an example:<?php
function christmasGreeting($name) {
echo "Happy Christmas, $name!";
}
$season = "christmas";
$functionType = "Greeting";
call_user_func($season . $functionType, "McClane");
// Output: "Happy Christmas, McClane!"
$season
and the string $functionType
, which gets us "christmasGreeting". Now we can call the function christmasGreeting
by passing it as an argument to call_user_func
. Any following arguments passed to call_user_func
will be passed on to the function.<?php
$greeting = function ($name) {
return "Hello, $name!";
};
function birthdayGreetings($name, callable $greeting)
{
echo $greeting($name) . " Happy birthday!\n";
}
birthdayGreetings('DROP TABLE', $greeting);
// Output: Hello, DROP TABLE! Happy birthday!