是否可以在 PHP 中获取方法中的语句


Is it possible to get the statements within a method in PHP?

function mainFunction() {
  functionA(5, "blah");
  functionB("ok", "whatever");
}

如何编写返回mainFunction函数的函数GetFunctions

如何使用 mainFunction 中给出的参数调用它们?

如何称呼它们如下?

foreach (GetFunctions(mainFunction) as $function) {
  print "Calling function $function: ";
  call($functionA); // called with parameters(5, "blah")
}

在 PHP 5.2.8 中工作

编辑:好的,这里有一个更完整的解释。我试图保持简单以使其易于理解,但显然这不是一个好主意。

目标是调用给定静态方法中的每个断言。我正在编写一个测试框架。每个断言都返回 true 或 false。

我按如下方式调用这些方法。

$methods = get_class_methods('LibraryTests');
foreach ($methods as $method) {
    if ( StartsWith($method, 'Test') ) {
        print "calling: " . $method . ": ";
        call_user_func('LibraryTests::' . $method);
    }
}   

上面的代码调用类中的每个方法,但我想单独调用每个断言并跟踪结果(真/假(。 CallAssertion应该调用每个断言(例如TestUnit::AssertEqual(GetFormattedHour(5), "5 PM");(。这就是我要问的方法。

这是类:

class LibraryTests extends TestUnit {
    static $success = 0;
    static $failure = 0;
    static $total = 0;
    static function CallAssertion($assertion) {
        self::$total += 1;
        if ($assertion) { self::$success += 1; }
        else { self::$failure += 1; }
    }
    static function TestGetFormattedHour() {
        TestUnit::AssertEqual(GetFormattedHour(5), "5 PM");
        TestUnit::AssertEqual(GetFormattedHour(16), "4 PM");
    }

那么,问题是,如何编写CallAssertion?

你不能。

相反,创建一个类并使用反射来获取其方法。

无论如何,您需要弄清楚为什么这是必要的,并查看是否可以使用完全不同的方法。

(如果这是出于调试目的,您可以使用debug_backtrace进行检查,但其目的不是调用您在问题中所述的函数。

嗯,你实际上想解决什么问题。对我来说,这听起来像您正在尝试在运行时检查调用堆栈。如果是这样,我建议只使用debug_backtrace()(src(。

不过,我不建议在生产中多次使用该函数,因为它对您的代码造成了相当大的打击。

一种可能性是对包含 main_function 的 PHP 文件进行file_get_contents,然后通过它来解析main_function及其调用的函数。当然,我不知道你的情况,所以这可能行不通。

您可以使用以下命令执行此操作:

http://php.net/manual/en/function.token-get-all.php

可能是个坏主意,但祝你好运!