“isset 构造”有捷径吗?
我经常写这行代码:
$myParam = isset($params['myParam']) ? $params['myParam'] : 'defaultValue';
通常,对于嵌套数组来说,它会使该行变得很长。
我可以把它改短一点吗?
I'm writing quite often this line of code:
$myParam = isset($params['myParam']) ? $params['myParam'] : 'defaultValue';
Typically, it makes the line very long for nested arrays.
Can I make it shorter?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
但请务必通过引用传递变量,否则代码将产生 E_NOTICE。另外,这里有意使用 if/else 而不是三元运算符,因此如果您使用 PHP <<,则可以共享 zval。 5.4.0RC1。
Be sure to pass the variable by reference though, otherwise the code will produce a E_NOTICE. Also the use of if/else instead of a ternary operator is intentional here, so the zval can be shared if you are using PHP < 5.4.0RC1.
PHP 7 将包含正是这样做的
??
运算符。请参阅 https://wiki.php.net/rfc/isset_ternary,示例:
PHP 7 will contain
??
operator that does exactly that.See https://wiki.php.net/rfc/isset_ternary, example:
是的,通过制作代理功能,但这真的值得吗?
此外,isset 是一种语言构造,因此将其包装在代理函数中将会降低性能,尽管这种降低可能不是微不足道的(甚至不值得一提)。
Yes, by making a proxy function, but is it really worth it?
Also,
isset
is a language construct, so wrapping it in a proxy function will degrade performance, although the degradation will likely be less than trivial (not even really worth mentioning.)这就是我使用的:
This is what I use:
从 PHP 5.3 开始,您可以使用:
但是请注意,
$params['myParam']
和isset($params['myParam'])
并不是 100%相同的。As of PHP 5.3 you can use:
Note, however, that
$params['myParam']
andisset($params['myParam'])
are not 100% the same.我使用了这个小魔法类,它作为变量工作,
然后在文档中您可以轻松地将它用作任何其他变量,例如
$post->name
$post->somelist [2]
或使用默认值$post->name("John Doe")
,之后您将其返回并存储。I'm using little this little magic class which works as variable
then in document you can use it easily as any other variable so for example
$post->name
$post->somelist[2]
or with default value$post->name("John Doe")
and after that you got it returned as well as stored.我知道这不会为您缩短任何内容,但我想我只是分享这个,我在我的应用程序中经常使用它来确保某些内容已设置并具有值。
然后...
I know this doesn't shorten anything up for you but thought I'd just share this, I use this alot in my applications to make sure something is set and has a value.
Then...
不,不幸的是,你不能。不是以一种体面的方式。你至少必须在性能上做出让步。
更新:从 PHP7 开始,
??
就可以做到这一点。请参阅https://wiki.php.net/rfc/isset_ternaryNo. Unfortunately, you can't. Not in a decent way. You'll at least have to give in on performance.
Update: since PHP7,
??
will do just that. See https://wiki.php.net/rfc/isset_ternary如果你必须经常这样做,那么你可能没有抓住重点。
事实上,变量应该在使用之前定义。
因此,不应该出现参数未定义的情况。
只需创建一个默认的参数文件,并初始化每个变量。
稍后在某些情况下可以更改它,但它永远不会是未定义的。
明白了吗?
You if you have to do it often, you are probably missing the point.
In fact, variables should be defined before use.
So, there oughtn't be a case when you have your param undefined.
Just create a default params file, and initialize every your variable.
later it can be changed under some circunstances but it never be undefined.
Got the idea?