...

View Full Version : what is question mark



zodehala
01-04-2008, 04:18 PM
what is question mark ? (what is its task ?)

would you give me a sample



$link = $this->functions[$usepconnect ? 'pconnect' : 'connect']("$servername:$port", $username, $password);

mlse
01-04-2008, 04:23 PM
Hi,

The example you have there can be re-written as follows:



if ($usepconnect)
{
$index = "pconnect";
}
else
{
$index = "connect";
}

$link = $this->functions[$index]("$servername:$port", $username, $password);


That's all there is to it! Very simple :) It is just quicker to use the (condition) ? (true) : (false) notation.

aedrin
01-04-2008, 04:24 PM
It's a ternary operator (meaning it involves 3 operands).

It's a simplified if statement.



$result = isset($variable) ? $variable : 'default';


Can also be written as.



if (isset($variable)) {
$result = $variable;
} else {
$result = 'default';
}


You can see it saves some typing, and quite a few common languages have this feature so it's okay to use when helpful (since it's not language specific).

One of the benefits is that you can put the ternary operator inline.



echo 'Your cart contains ' $total . ' item' . ($total == 1 ? '' : 's');

anarchy3200
01-04-2008, 04:25 PM
Very slow today! Just repeat of the above...



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum