如何在 PHP 中编写速记设置器?

发布于 2024-12-28 19:47:32 字数 345 浏览 3 评论 0 原文

我很好奇有没有办法用 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?";

但这似乎不起作用。对于这种情况,有人有什么很酷的技巧吗?

谢谢!

I'm curious is there a way to write a shorthand setter in PHP. My primary quest when writing code is to make it as tight as possible and I think the following is kind of cumbersome:

$value = "Which array do I go in?";
if(true)
    $arr_1[] = $value;
else
    $arr_2[] = $value;

Is there a better way to write that? I tried to use the shorthand if:

(true)?$arr_1[]:$arr_2[] = "Which array do I go in?";

But that doesn't seem to work. Anyone have any cool tricks for this type of situation?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

乱了心跳 2025-01-04 19:47:32

对于您想要做的事情没有简写。您还应该意识到,使代码“尽可能紧凑”通常是以牺牲可读性为代价的。

编辑:有一些丑陋的黑客可以做你想做的事,但我强烈建议不要这样做。例如:

$GLOBALS[cond ? 'varname1' : 'varname2'] = $value;

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.:

$GLOBALS[cond ? 'varname1' : 'varname2'] = $value;
可爱暴击 2025-01-04 19:47:32

另一个黑客是:

$arr = ($cond ? &$arr_1 : &$arr_2);
$arr[] = 'Which array do I go in';

它有两行,但不需要全局并且可以在函数中工作。然而,为了可读性,使用 if 语句可能更好。 (注意:&正在引用变量,这就是它起作用的原因)。另一个(这可能会让您了解三元运算符的工作原理)是:

$cond ? $arr_1[] = $value : $arr_2[] = $value;

您看到三元运算符仅评估(运行代码路径)成功评估(在 ? 的右侧,如果为 true,则在 的右侧:如果错误)。但是,如果您认为这比使用“if”更快,那么您错了,那么不太“严格”的代码实际上会执行 更好

Another hack would be:

$arr = ($cond ? &$arr_1 : &$arr_2);
$arr[] = 'Which array do I go in';

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:

$cond ? $arr_1[] = $value : $arr_2[] = $value;

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.

待天淡蓝洁白时 2025-01-04 19:47:32

另一种选择(例如,如果您不能/不想使用全局变量)。

${$cond?'arr_1':'arr_2'}[] = $value;

Another option (e.g. if you can't/don't want to use globals).

${$cond?'arr_1':'arr_2'}[] = $value;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文