doubi7496 2014-09-23 12:57 采纳率: 0%
浏览 78

使用PHP的三元运算符作为控制结构的危险/副作用

A coworker frequently uses PHP's ternary operator as a control structure, rather than the RHS of an expression. One such example:

list==''?list=val:list=list+','+val;

(In that example, the statement is called in a loop to add values to a string, ensuring the comma separator doesn't appear if there's only one item.) In essence, he relies on the expression evaluation to do work, and throws away the expression result.

Aside from the fact that it's hard on the eyes, is there any reason to avoid this construct? It's syntactically legal; and it executes correctly. But I'm certain the ternary operator wasn't designed to be used in this manner, and I wonder if there are consequences to doing so.

  • 写回答

1条回答 默认 最新

  • dtdr57046 2014-09-23 13:01
    关注

    It will work fine, and I don't see any problem with it apart from readability.

    If you think it's hard on the eyes, replace this loop and line with a call to the implode function.

    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗