PHP 三元运算符说明
我经常使用三元运算符,但我无法在文档中找到有关此的任何内容,并且我一直想知道它。
下面是一个可能的例子:
echo ($something->message ? $something->message : 'no message');
正如你所看到的,如果 $something->message 正确,我们返回 $something->message,但为什么要写两次呢?有没有办法做类似的事情:
echo ($something->message ? this : 'no message');
现在我不太精通编程理论,所以可能有一个原因,前者不能用“this”之类的东西引用,但为什么不呢?这不会简化三元运算符的使用吗?对于像我的例子这样的东西,它是非常无用的,但是假设
echo (function(another_function($variable)) ? function(another_function($variable)) : 'false');
我无法找到任何方法来做到这一点,所以我假设这是不可能的,如果我错了,请通知我,否则:为什么不呢?为什么这是不可能的,技术原因是什么,或者只是从未发生过?我应该将其声明为变量然后针对该变量进行测试吗?
I use the ternary operator quite often but I've not been able to find anything in the documentation about this and I've always wondered it.
The following is a possible example:
echo ($something->message ? $something->message : 'no message');
as you can see, if $something->message is correct, we return $something->message, but why write it twice? Is there a way to do something like:
echo ($something->message ? this : 'no message');
Now I'm not well versed in programming theory, so it's possible that there is a reason that the former cannot be referenced with something like "this" but why not? Would this not stream line the use of the ternary operator? For something like my example it's pretty useless, but let's say it's
echo (function(another_function($variable)) ? function(another_function($variable)) : 'false');
I'm unable to find any way to do this, so I'm assuming it's not possible, if I'm wrong please inform me, otherwise: why not? Why is this not possible, what's the technical reason, or is it just something that never happened? Should I be declaring it as a variable and then testing against that variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来源
例如
相同
与 智者之言
如果您要依赖于
TRUE
的类型转换,那么了解什么是很重要的WILL 类型转换为TRUE
以及什么不会。也许值得温习一下 PHP 的 类型杂耍 并阅读类型转换表。例如,(bool)array()
为FALSE
。Source
For example
Is the same as
Word for the wise
If your going to be depending on typecasting to
TRUE
it's important to understand what WILL typecast toTRUE
and what won't. It's probably worth brushing up on PHP's type juggling and reading the type conversion tables. For example(bool)array()
isFALSE
.