【问题标题】:PHP long ternary operator line and 120 char line long PSR rulePHP 长三元运算符行和 120 字符行长 PSR 规则
【发布时间】:2020-06-10 11:11:47
【问题描述】:

有没有一种格式化长三元运算符行的好方法?比方说:

$order = new Order($this->isProfessionalChildCollaborator($this->getUser()) ? $this->getUser()->getParent() : $this->getUser());

根据 PSR 中定义的每行 120 个字符,这太长了。我应该这样做:

$order = new Order(
    $this->isProfessionalChildCollaborator($this->getUser()) ?
    $this->getUser()->getParent() :
    $this->getUser()
);

或者还有其他最佳做法吗?

【问题讨论】:

  • 缓存 $this->getUser() 调用以减少字符。您还可以将isProfessionalChildCollaborator 包装在一些较小的方法名称中。
  • 是否使用if 子句而不是三元选项?
  • 据我所知,您的建议@vivek_23 和@kerbholz 是更多的解决方法。想象这个表达式是不可约化的,问题仍然存在。 if 的使用可能是最后一个阶段,但我的问题是关于三元的格式指南。
  • @nbonniot 好吧,我通常不会用三元 if 条件初始化构造函数。所以我从来没有遇到过这些挑剔的东西。我通过它们并在构造函数本身中决定它们或利用子类型多态性

标签: php conditional-operator psr-2


【解决方案1】:

PSR 中对此没有规定,但我更喜欢 this style, described in

$documentProcessingIndicatorId = $object->isProcessingDocument()
    ? $object->getDocumentProcessingIndicatorId()
    : null;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-04
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 2013-01-15
    • 2012-12-19
    • 1970-01-01
    相关资源
    最近更新 更多