【问题标题】:Using the PHP ternary operator to return a specific value [closed]使用 PHP 三元运算符返回特定值 [关闭]
【发布时间】:2012-08-30 08:16:02
【问题描述】:

我已经用谷歌搜索了这个并浏览了堆栈溢出。我正在尝试缩短我的代码,并且我在下面有这个工作方法,我想用三元样式重写。有人可以告诉我这是否可能,如果可以,我做错了什么。谢谢。

public function __get($field){ //refactor this using ternary method
    if($field == 'user_id'){
        return $this->uid;
    } else {
        return $this->fields[$field];
    }
}

我是从这个开始的:

($field == 'user_id') return $this->uid : return $this->fields[$field];

它给了我一个意外的返回错误。

我尝试使用另一个堆栈溢出解决方案,该解决方案在值之前列出了返回值,但没有奏效。

return $field == 'user_id' ? $this->uid : $this->fields[$field];

这给了我一些关于意外公共的其他错误,比如我的方法没有正确关闭。

【问题讨论】:

  • 你最后的代码 sn-p 没问题。你的错误信息听起来像是你做错了什么
  • 后者绝对是正确的方法;也许您可以分享确切的错误消息。
  • 你能发布你得到的确切错误吗?
  • 顺便说一句,意外返回错误很可能是由于缺少?
  • 能把方法的完整代码贴出来吗?截至目前,我猜你的右大括号数量可能是错误的。

标签: php operator-keyword ternary


【解决方案1】:

我猜是这样的;您将代码重构为:

public function __get($field){ //refactor this using ternary method
        return $field == 'user_id' ? $this->uid : $this->fields[$field];
    }
}

public function otherfunction() { /* ... */ }

大括号不匹配,因此它关闭类定义,下一个解析器错误是'unexpected public' :)

【讨论】:

  • 很有可能。我只是有同样的想法:)
猜你喜欢
  • 1970-01-01
  • 2020-02-09
  • 2020-01-25
  • 2017-03-28
  • 1970-01-01
  • 2016-03-09
  • 2018-07-24
  • 2014-09-24
相关资源
最近更新 更多