如何在 PHP 中编写速记设置器?
我很好奇有没有办法用 PHP 编写速记设置器。我编写代码时的首要任务是使其尽可能紧凑,我认为以下内容有点麻烦:
$value = "Which array do I go in?";
if(true)
$arr_1[] = $value;
else
$arr_2[] = $value;
有更好的方法来编写它吗?我尝试使用简写 if:
(true)?$arr_1[]:$arr_2[] = "Which array do I go in?";
但这似乎不起作用。对于这种情况,有人有什么很酷的技巧吗?
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于您想要做的事情没有简写。您还应该意识到,使代码“尽可能紧凑”通常是以牺牲可读性为代价的。
编辑:有一些丑陋的黑客可以做你想做的事,但我强烈建议不要这样做。例如:
There is no shorthand for what you are trying to do. Also you should realize that making code "as tight as possible" often comes at the cost of readability.
EDIT: There is some ugly hacks to do what you want, but I would strongly recommend against. E.g.:
另一个黑客是:
它有两行,但不需要全局并且可以在函数中工作。然而,为了可读性,使用 if 语句可能更好。 (注意:&正在引用变量,这就是它起作用的原因)。另一个(这可能会让您了解三元运算符的工作原理)是:
您看到三元运算符仅评估(运行代码路径)成功评估(在 ? 的右侧,如果为 true,则在 的右侧:如果错误)。但是,如果您认为这比使用“if”更快,那么您错了,那么不太“严格”的代码实际上会执行 更好。
Another hack would be:
it's two lines but it doesn't require global and would work in a function. However for readability it is probably better to use an if statement. (Note: the & is making a reference to the variable, which is why this works). Another (which might make you understand HOW the ternary operator works) would be:
You see the ternary operator only evaluates (runs the code path) of the successful evaluation (on the right side of the ? if true, on the right side of : if false). However if you think this is faster than using 'if' you are wrong, your less 'tight' code will actually perform better.
另一种选择(例如,如果您不能/不想使用全局变量)。
Another option (e.g. if you can't/don't want to use globals).