gpt4 book ai didi

php - 如何在 PHP 中传递标签?

转载 作者:可可西里 更新时间:2023-11-01 00:41:18 25 4
gpt4 key购买 nike

这个故事的背景很长,所以简而言之 -- 我知道 goto 不好,但我别无选择,因为...PHP 缺少逗号运算符。

我有这样的模式——常规函数,入口点作为标签给出,在它里面有一个小的 lambda,它需要 goto 到那个入口点。像这样(不正确的代码):

  function water()
{
_Entry_point_2_0:
// ... some code
(function() { /*...*/ ;goto _Entry_point_2_0;})();
// ... some code
}

我不能直接跳过函数边界,所以我的下一个想法是从 lambda 返回标签并将其用作 goto 的“值”。像这样:

  function water()
{
_Entry_point_2_0:
// ... some code
goto (function() { /*...*/ ;return '_Entry_point_2_0';})();
// ... some code
}

这是行不通的。将整个 goto 评估为字符串 eval ('goto _Entry_point_2_0;') 也不起作用。

疯狂的部分是我事先知道标签,所以你可以问为什么我不能这样写整个函数:

  function water()
{
_Entry_point_2_0:
// ... some code
(function() { /*...*/ ;})();
goto _Entry_point_2_0;
// ... some code
}

问题出在逻辑上——执行 lambda goto 现在生成 2 个表达式,而不是一个。我需要在一个表达式中实现它——执行 lambda 和 goto 必须打包在单个表达式中。

我也不能递归调用 main 函数,因为这是整个工作的重点,以避免递归调用:-)。

还有哪些其他方法可以实现这一点?

UPDATE 1 也许我换个说法——我想用 goto 实现的是 continue my_function。从内部函数(即 lambda)的边界处执行。

更新 2 主要目标是循环 main 函数,所以它几乎等同于:

  function water()
{
_Entry_point_2_0: while (true)
{
// ... some code
continue (function() { /*...*/ ; return '_Entry_point_2_0'; })();
// ... some code
}
}

“差不多”有两个原因。我仍然和以前一样遇到标签问题,而且现在我遇到了在何处将 break 添加到循环中的问题。

最佳答案

因此您不能从匿名/lambda 函数中跳过循环迭代。但是您可以返回一个值,比较主函数中的值,然后从那里跳过迭代。听起来很简单,对吧?

编辑:如果你也想摆脱兰巴舞,你可以使用相同的策略。

function water() {
$lambda = function() { /*...*/; };

while (true) {
// Call the lambda function and store the return value.
$return = $lambda();

// If the return value was 'skip this iteration', well... skip it.
// Note: I'd normally compare to false, null or similar.
if ($return == 'skip this iteration') {
continue;
}
elseif ($return == "we're done!") {
break;
}

// Do stuff here.
}
}

I need to make it in one expression -- execute lambda and goto has to be packed in single expression.

因此,根据您上次的评论,我现在部分理解您为什么有此要求。但目前还不完全清楚。你已经编写了一个脚本来将这段代码注入(inject)到一些预先存在的函数中并且不知道周围的环境。但是 goto 标签已经到位了吗?无论如何,也许您的问题就这么简单:您希望代码只有一行。但这是可能的,代码可以在 PHP 中仅跨越一行。它不是最漂亮的,但它工作得很好。

function water() {
while (true) {
if (function() { /*...*/; }() == 'skip this iteration') { continue; /* Or goto */ }
// Do stuff here.
}
}

关于php - 如何在 PHP 中传递标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36216763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com