开发者

conditional operator shortcut in PHP?

Does anybody know if there is a shortcut for the following statement in PHP?

$output = isset($some_value) ? $some_value : "Some Value Not Set";
echo $output;

This something that I often run into, where $some_value is actually very long and possibly involves a function, such as:

$output = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value) ? $this->db->get_where('my_db',array('id'=>$id))->row()->some_value) : "Some Value Not Set";开发者_运维百科
echo $output;

It seems that there should be an operator or function that does this. I could easily write one, and I am not looking for that answer, but rather if anybody knows of a built-in shortcut.


Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

http://php.net/manual/en/language.operators.comparison.php


if you need to reuse the long expression from the test after the ?, you can assign it to a variable inside the test (because assignments are expressions returning the assigned value) and use this variable after the ?:

$output = ($some_value = $this->db->get_where('my_db', array('id' => $id))->row()->some_value))
  ? $some_value 
  : "Some Value Not Set";
echo $output;


You should be setting a variable with the results of your database call before using the conditional operator for this purpose. Your example makes the database call twice.

For example:

$output = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value);
$output = $output ? $output : "Some Value Not Set";
echo $output;

And with that established, this is a good case where it's really wiser to not use the conditional operator, which really isn't meant to be used as a general purpose if-then shortcut.


You seem to be afraid of whitespace. Use it! Liberally! Your code is much eaiser to read if you add a space before and after the question mark and the colon, respectively. If your statements get too long, add a newline. Try it, it won't hurt you.


I do believe that the conditional operator is the shortcut :) For the sake of saving function calls and readability, I suggest saving the value to a variable first.

$some_value = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value);
$output = $some_value ? $some_value : "Some Value Not Set";
echo $output;


Best way is to:

$output = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value)
echo $output =($output)?$output:"Some Value Not Set";

Only executes once then!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜