简体   繁体   English

如何在循环中“取消声明”自定义 function

[英]How to 'undeclare' a custom function in a loop

I am collecting a series of php files and testing to see if a single function returns valid output.我正在收集一系列 php 文件并测试以查看单个 function 是否返回有效的 output。 To facilitate the process, all their functions are named identically.为了简化该过程,它们的所有功能都以相同的名称命名。 So then I can run:那么我可以运行:

foreach($fileList as $file) {

    require($file);
    echo $testFunction();

}

The problem is that php throws an error 'Cannot redeclare function' since the second file's function is named the same as the first.问题是 php 抛出错误“无法重新声明函数”,因为第二个文件的 function 与第一个文件的名称相同。 What I want to do is 'undeclare' a function after I test its output but I know this isn't possible and I'm trying to handle this procedurally.我想要做的是在测试 output 后“取消声明” function 但我知道这是不可能的,我正在尝试通过程序处理这个问题。 unlink($file) does not remove the instance of the function, unfortunately.不幸的是,unlink($file) 不会删除 function 的实例。 Is there a simple way to handle this without using an OOP approach?有没有不使用 OOP 方法的简单方法来处理这个问题?

You can execute the files in another process, for example (assuming $testFunction is defined in the files), you could do something like this (assuming you are running on Linux):您可以在另一个进程中执行文件,例如(假设在文件中定义了$testFunction ),您可以执行以下操作(假设您在 Linux 上运行):

foreach($fileList as $file) {
    // load code from the current file into a $code variable,
    // and append a call to the function held in the $testFunction variable
    $code = file_get_contents($file) . "\n" . '$testFunction()';

    // save this to a temporary file
    file_put_contents('/tmp/test-file.php', $code);

    // execute the test file in a separate php process,
    // storing the output in the $output variable for examination
    $output = shell_exec('/tmp/test-file.php');

    // examine output as you wish
}

unlink('/tmp/test-file.php');
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM