由于返回 ?:"http" 导致 PHP 服务器错误
我是一个 php 新手,我遇到了一个问题,我希望有人能为我提供帮助。
当我将包含以下内容的 .php 上传到我的服务器并将其加载到 Chrome 浏览器中时,似乎没有任何问题。
<?php
class AppInfo {
public static function getHome () {
return ($_SERVER['HTTP_X_FORWARDED_PROTO'])."://" . $_SERVER['HTTP_HOST'] . "/";
}
但是,
当我上传包含下面非常相似的代码的 .php 文件时(区别在于存在 ?:"http"),chrome 返回服务器错误(粘贴在代码下方)
<?php
class AppInfo {
public static function getHome () {
return ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?: "http") . "://" . $_SERVER['HTTP_HOST'] . "/";
}
}
错误:
服务器错误 网站在检索“Url”时遇到错误,可能已关闭以进行维护或配置不正确。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该将其更改为
因此,这意味着如果
($_SERVER['HTTP_X_FORWARDED_PROTO']
存在,则使用它,否则使用http
。You should change it to
So this would mean that if
($_SERVER['HTTP_X_FORWARDED_PROTO']
is there use it else usehttp
.我相信您正在尝试使用所谓的 三元运算符。该运算符需要以下语法:
文档指出,仅当您使用 PHP 5.3 或更高版本时,您才可以省略中间子句(“如果为真则做什么”子句)。在我看来,这是不好的做法。我不知道有任何其他编程语言允许这种快捷方式,它只会使阅读代码变得更加困难(特别是如果您在编写代码一年或更长时间后才阅读它)。最好编写(如果可能)向后兼容的代码;因此,它会更加便携。
更新:我在维基百科上读到了一些关于三元运算符的内容,其他一些语言确实有这样的快捷方式(例如,存在 C 的 GNU 扩展)。我仍然认为使用快捷方式是不好的;我想到了语句评估导致副作用的情况。
I believe you are trying to use what's called the ternary operator. This operator expects the following syntax:
The documentation states that you may omit the middle clause (the 'what to do if true' clause), only if you're using PHP 5.3 or later. In my opinion, this is bad practice. I'm not aware of any other programming languages that allow that shortcut, and it only makes reading your code that much more difficult (especially if you're reading it a year or more after you wrote it). It's best to write code that is (where possible) backwards compatible; it will be that much more portable as a result.
Update: I read a little about the ternary operator on Wikipedia, and a few other languages do have shortcuts like this (a GNU extension for C exists, for example). I still think using the shortcut is bad; the case where statement evaluation results in side effects springs to mind.