if(isset($_GET['tag'])) {
define("NJ_THISCATSUB","tag: ".$_GET['tag']);
}
任何人都知道以下代码段的简短if版本?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- doue9730 2012-11-16 17:04关注
There may be a couple of ways, none of which would really be recommended instead of what you have.
Except for omitting the
{}
you can't really shorten by packing it into a ternary operator (for example) ifNJ_THISCATSUB
is assumed to be not defined when$_GET['tag']
is unset. Stick with what you have -it is clear and readable, and correct.// About as short as you're going to get: // In other words, your method is fine and I don't recommend changing it. if(isset($_GET['tag'])) define("NJ_THISCATSUB","tag: ".$_GET['tag']);
Ternary example:
However,
NJ_THISCATSUB
were defined as a null or empty value in absence of the$_GET['tag']
, you could use a ternary:// Define as NULL, absent $_GET['tag'] (not the same as what you have!) define('NJ_THISCATSUB', isset($_GET['tag']) ? "tag: ".$_GET['tag'] : NULL);
This doesn't appear to be the behavior you are after though.
By short-circuit
&&
You could take advantage of the logical
&&
and to it this way, saving a couple of characters. If the left side of&&
is true, it proceeds to check the right side, and must evaluate thedefine()
to do so. If the left side isFALSE
, it will short circuit and not evaluate the right. Therefore this works:isset($_GET['tag']) && define("NJ_THISCATSUB","tag: ".$_GET['tag']);
The above is kind of unconventional in PHP though (if there is a such thing as convention in PHP), and would be more at home in languages like JavaScript or Ruby. You're far more likely to encounter PHP code using the simpler
if ()
you initially posted.// Simple console demonstration // Define X if $x is set: php > $x = 123; php > isset($x) && define('X', $x); php > echo X; // 123 // Define Y if $y is set (it isn't)... php > isset($y) && define('Y', $y); php > echo Y; PHP Notice: Use of undefined constant Y - assumed 'Y' in php shell code on line 1 Notice: Use of undefined constant Y - assumed 'Y' in php shell code on line 1 // Oops, Y is not defined as a constant...
解决 无用评论 打赏 举报
悬赏问题
- ¥15 python的qt5界面
- ¥15 无线电能传输系统MATLAB仿真问题
- ¥50 如何用脚本实现输入法的热键设置
- ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
- ¥30 深度学习,前后端连接
- ¥15 孟德尔随机化结果不一致
- ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
- ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
- ¥15 谁有desed数据集呀
- ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100