测试和回显而不重复?
这是一件小事,但却困扰了我一段时间。我绞尽脑汁想找到一种方法来编写这样的语句,而无需重复任何代码。例如:
echo isset($array[0])? $array[0]: 'not set';
$var = empty($other_var)? '$other_var not set': $other_var;
是否有某种我不知道的测试和返回(对于前者)或测试和设置(对于后者)运算符?这看起来似乎是一个小问题,但重复似乎没有必要,并且可能会导致很长的线路,从而使维护变得复杂。想一想:
$another_var = array_key_exists($array[Utility::FindIndex($username)][Constants::App_CRITERION], $haystack[NthDimension('my dimensional indicator')])? $array[Utility::FindIndex($username)][Constants::App_CRITERION], $haystack[NthDimension('my dimensional indicator')]: 'not set';
是的,是的,上面这句话完全是人为的,但发生这样的事情并非不可想象。对我来说,没有一种方法可以在不重复的情况下测试某些东西并分配它的值(如果是的话),这对我来说似乎很奇怪。
This is a minor thing, but it's been bugging me for a while. I've wracked my brain for a way to write statements like this without any repetition of code. For example:
echo isset($array[0])? $array[0]: 'not set';
$var = empty($other_var)? '$other_var not set': $other_var;
Is there some sort of test-and-return (for the former) or test-and-set (for the latter) operator I don't know about? This may seem like a minor point, but the duplication seems unnecessary and can lead to very long lines that can complicate maintenance. Consider:
$another_var = array_key_exists($array[Utility::FindIndex($username)][Constants::App_CRITERION], $haystack[NthDimension('my dimensional indicator')])? $array[Utility::FindIndex($username)][Constants::App_CRITERION], $haystack[NthDimension('my dimensional indicator')]: 'not set';
Yes, yes, the above line is totally contrived but it's not unthinkable that something like this could occur. It just seems strange to me that there isn't a way to test something and assign it's value (if true) without repetition without repetition.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它不会处理 isset () 情况,这是此模式的主要用例,但 PHP 5.3 确实有三元运算符的缩写形式。
可以缩短为
我在文档中找不到它,奇怪的是,但这里有一个关于它的问题: PHP 5.3 中的 ?: 是什么?
It won't handle the isset () case, which is a main use case for this pattern, but PHP 5.3 does have a short form for the ternary operator.
can be shortened to
I couldn't find it in the docs, strangely, but here's a question about it: What is ?: in PHP 5.3?
我认为在 PHP 6 中计划有一个名为
issetor
或类似的函数。但我不记得名字了。不管怎样,PHP 6 已经死了。所以,你自己写吧:
如果你想让它更抽象,看看这个:
如果你想将额外的变量传递给你的条件函数而不总是
使用
闭包,你可以添加另一个参数。 (请注意,我没有使用参数数组和 call_user_func_array ,因为您可能无法使用它传递每个引用,但显然您可以扩展代码,以便它这样做。)I think in PHP 6 there was a function planned called
issetor
or something similar. But I can't remember the name. And PHP 6 is dead either way.So, write it yourself:
If you want to make it even more abstract, look at this:
If you want to pass additional variables to your condition function without always
use
ing closures you may add another argument. (Note I didn't use an argument array andcall_user_func_array
, because you may not pass per reference using it, but obviously you may extend the code so it does so.)