PHP中“?",“()"和“:"符号的含义是什么? [英] What is the meaning of the '?', '()', and ':' symbols in PHP?

查看:227
本文介绍了PHP中“?",“()"和“:"符号的含义是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于想起要问什么了.我从来没有真正得到过什么?像这样定义变量时要做的事:

I've finally remembered what to ask. I never really got what : and ? do when a variable is being defined like this:

$ip = ($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];

如您所见,那里有?和:和()

As you can see there is ? and : and ( )

任何人都可以给我简要介绍一下为什么以及如何使用它们吗?

Could anyone give me a brief detail about why and how they are used for?

推荐答案

表达式如下:

$var = (condition) ? if_true : if_false

?: 三元运算符 .如果condition为true,则将为$var分配值if_true;否则,为if_true.否则将为其分配值if_false.

?: is the ternary operator. If condition is true, $var will be assigned the value if_true; otherwise it will be assigned the value if_false.

在您的特定情况下:

  • 这会将X-Forwarded-For HTTP标头的值分配给$ip(如果存在);否则它将使用远程地址本身.

  • This assigns the value of the X-Forwarded-For HTTP header to $ip if it exists; otherwise it uses the remote address itself.

这通常用作获取客户端IP地址的一种方式.但是,请注意,通常这是一种检查客户端身份的糟糕方法.请参阅 这个StackOverflow问题 . (如果您需要确保用户之间不会互相干扰,请使用会话cookie或某种身份验证.)

This is usually used as a way to get a client's IP address. However, note that in general this is a terrible way to check for client identity. See this StackOverflow question. (Use session cookies or some sort of authentication if you need to make sure users don't clobber each other.)

也是HTTP_X_FORWARDED_FOR,而不是HTTP_X_FORWARD_FOR.

最后,HTTP_X_FORWARDED_FOR可以是用逗号分隔的IP地址列表,而不仅仅是一个,因此可能会成为错误.

Finally, HTTP_X_FORWARDED_FOR can be a comma-delimited list of IP addresses, not just a single one, so this has the potential to be a bug.

这篇关于PHP中“?",“()"和“:"符号的含义是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆