duanmianxue2687 2012-03-16 19:59
浏览 15
已采纳

是否有可能在PHP中的方法中获取语句?

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

How to write a function GetFunctions that returns the functions within mainFunction?

How to call them with the parameters given in mainFunction?

How to call them as follows?

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

Working in PHP 5.2.8

EDIT: OK, here's a more complete explanation. I tried to keep it simple to make it easy to understand, but apparently that wasn't a good idea.

The goal is to call each assertion within a given static method. I am writing a testing framework. Each assertion returns true or false.

I am calling the methods as follows.

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

The above code calls each method within the class, but I want to call each assertion individually and track the result (true/false). CallAssertion is supposed to call each assertion (such as TestUnit::AssertEqual(GetFormattedHour(5), "5 PM");). This is the method that I am asking about.

Here is the class:

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");
    }

So, the question is, how to write CallAssertion?

  • 写回答

4条回答 默认 最新

  • dongtanjian9310 2012-03-16 20:01
    关注

    You can't.

    Instead, create a class and use reflection to get its methods.

    Regardless, you'll want to figure out why this is necessary and see if there is an entirely different approach you can use.

    (If this is for debugging purposes, you can use debug_backtrace to inspect but its purpose is not for calling functions as you have described in your question.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图