本文介绍了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...) valueHowever, 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或更高版本,则必须使用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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 06:57