I don’t understand what the question mark does in this function:
function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL)
{
$device = is_null($coffeeMaker) ? "hands" : $coffeeMaker;
return "Making a cup of ".join(", ", $types)." with $device.\n";
}
echo makecoffee();
echo makecoffee(array("cappuccino", "lavazza"), "teapot");
It’s a ternary operator ( a lot of programming languages have one ) and it’s basically a short version of an if-then-else statement.
if ( is_null($coffeeMaker) ) {
$device = "hands";
} else {
$device = $coffeemaker;
}
is the statement as an if statement.
1 Like
[off-topic]
I can’t remember seeing join(…) used before.
The alias is so much more intuitive and readable than implode(…); which I always have to lookup for the needle and haystack.
Many thanks 
[/off-topic]
And what about the → in this:
<?php
function total_intervals($unit, DateInterval ...$intervals) {
$time = 0;
foreach ($intervals as $interval) {
$time += $interval->$unit;
}
return $time;
}
$a = new DateInterval('P1D');
$b = new DateInterval('P2D');
echo total_intervals('d', $a, $b).' days';
// This will fail, since null isn't a DateInterval object.
echo total_intervals('d', null);
?>
It’s called a T_OBJECT_OPERATOR
. You can find more on them on the PHP Manual page about Parser Tokens
You might find this page on StackOverflow useful too → http://stackoverflow.com/questions/2987963/what-does-do-or-mean-in-php
system
Closed
6
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.