三元或类似的东西来选择功能?
我正在使用 Drupal 的 PHP 自动化测试。该类有两个我关心的方法:pass()
和 fail()
。每个操作都会在结果页面上生成一行单独的行,指示特定操作是通过还是失败,例如,
if ( $value == "expected_value" ) {
$this->pass("Looking for expected value");
} else {
$this->fail("Looking for expected value");
}
我注意到上面的内容有点冗长。我想做一些类似三元赋值的事情,只是在我决定调用哪个函数的地方。比如:
$function = ($value == "expected_value") ? "pass" : "fail" ;
$this->$function("Looking for expected value.");
这是我表达这个逻辑的最简洁、最优雅的方式吗?我尝试过
$this->(($value == "expected_value") ? "pass" : "fail")("Looking for expected value.");
但出现解析错误。有没有办法将其简化为一行,例如三元赋值?
编辑 我认为的冗长不是 if-else
结构,而是我将同一消息重复两次。在我看来,应该有一种表达方式,我只声明一次消息。当然,我可以将它放在一个变量中,但这会占用额外的空间,而且我还传递了两次。
这是提出我的问题的另一种方式:有没有一种方法可以定义这个逻辑,同时只表达一次寻找期望值
?
I'm working with Drupal's automated testing in PHP. It's a class that has two methods I'm concerned about: pass()
and fail()
. Each one produces a separate line on a results page indicating whether a particular operation passed or failed, e.g.
if ( $value == "expected_value" ) {
$this->pass("Looking for expected value");
} else {
$this->fail("Looking for expected value");
}
What I notice about the above is that it's a bit verbose. I'd like to do something like ternary assignment, only instead where I decide which function to call. Something like:
$function = ($value == "expected_value") ? "pass" : "fail" ;
$this->$function("Looking for expected value.");
Is this the most concise, elegant way I can phrase this logic? I tried
$this->(($value == "expected_value") ? "pass" : "fail")("Looking for expected value.");
But I got a parse error. Is there a way to get it down to one line, like ternary assignment?
Edit The verboseness that I percieve is not the if-else
structure, but that I repeat the same message twice. It seems to me that there should be a way of expressing this where I only declare the message once. Of course I could put it in a variable, but that takes up extra space and I pass it twice, also.
Here's another way of framing my question: Is there a way I can define this logic while only expressing Looking for expected value
one time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会使用通常的 if-elseif 语句,因为它是最明显、可读的并且(也许只有我)它不是“冗长”,它只是一个 if-elseif >-声明。
然而
I would use the usual
if-elseif
-statement, because its the most obvious, readable and (maybe its just me) its not "verbose", its just anif-elseif
-statement.However
我认为你的原始代码是最好的可读性,但如果你想要更短的东西(虽然不一定优雅),你可以这样做:
I think that your original code is the best for readability, but if you want something shorter (though not necessarily elegant) you could do: