PHP语法.布尔运算符,三元运算符和JavaScript [英] PHP syntax. Boolean operators, ternary operator and JavaScript

查看:70
本文介绍了PHP语法.布尔运算符,三元运算符和JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我习惯于使用以下后备评估

In JavaScript I have a habit of using the following fallback evaluation

var width = parseInt(e.style.width) || e.offsetWidth() || 480

表示width将获得最后一个非零(non-null ...)值 但是,在php中我无法编写

meaning width will get the last non-zero (non-null...) value However, in php I can't write

$a = $_GET['id'] || 1;

我必须这样写

$a = $_GET['id']?$_GET['id']:1;

这是不好的,因为$_GET['id']被两次评估

Which is bad because $_GET['id'] is evaluated twice

有什么建议吗?

推荐答案

如果您拥有PHP 5.3,则可以轻松做到:

If you have PHP 5.3 you can simply do:

$a = $_GET['id'] ?: 1;

根据PHP手册:

自PHP 5.3起,可以省略三元运算符的中间部分.表达式expr1?:如果expr1的计算结果为TRUE,则expr3返回expr1,否则返回expr3.

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.

如果您没有PHP 5.3或更高版本,则必须使用Sarfraz(或更好的delphist)的建议.但是,在较大的应用程序中,我倾向于以某种方式包装请求变量,以便可以在检索请求的函数的参数中指定默认值.这样做的好处是它更干净(更易于理解),并且如果$ _GET变量中不存在索引,它也不会生成警告,因为我可以使用isset之类的东西来检查数组索引是否存在.我最终得到这样的东西:

If you don't have PHP 5.3 or greater you would have to use Sarfraz's (or better, delphist's) suggestion. However, in larger applications I tend to have the request variables wrapped in a way that I can specify a default value in the argument to the function retrieving the request. This has the advantage that it is cleaner (easier to understand) and it doesn't generate warnings if the index doesn't exist in the $_GET variable as I can use things like isset to check if the array index exists. I end up with something like:

这篇关于PHP语法.布尔运算符,三元运算符和JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆