【发布时间】: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