PHP 中的条件运算符快捷方式?
有谁知道PHP中以下语句是否有快捷方式?
$output = isset($some_value) ? $some_value : "Some Value Not Set";
echo $output;
这是我经常遇到的情况,其中 $some_value 实际上很长,并且可能涉及一个函数,例如:
$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;
似乎应该有一个运算符或函数来执行此操作。我可以轻松地写一个,我不是在寻找答案,而是在寻找内置的快捷方式。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
http://php.net/manual/en/language.operators.comparison.php
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?
:在为此目的使用条件运算符之前,您应该使用数据库调用的结果设置一个变量。您的示例使数据库调用两次。
例如:
既然已经建立了,这是一个很好的例子,不使用条件运算符确实更明智,它实际上并不意味着用作通用的 if-then 快捷方式。
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:
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.
最好的方法是:
只执行一次!
Best way is to:
Only executes once then!