【问题标题】:Parse a string to extract function name and parameter for use with `call_user_func()`解析字符串以提取函数名称和参数以与 `call_user_func()` 一起使用
【发布时间】:2011-05-16 13:28:26
【问题描述】:

如何执行transaction(123) 函数?

API 的响应是:transaction(123)

我将它存储在 $response 变量中。

<?php

function transaction($orderid) {
  return  $orderid;
}

//api response
$response = "transaction(123)";

try {
  $orderid = call_user_func($response);
  echo  $orderid;
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

?>

【问题讨论】:

    标签: php


    【解决方案1】:

    根据manual page call_user_func() 应该在您的用例中使用两个参数调用。

    $orderid = call_user_func('transaction', 123);
    

    这意味着您必须从$response 变量中分别提取函数和参数:

    preg_match('/([\w\_\d]+)\(([\w\W]*)\)/', $response, $matches);
    

    将导致 $matches 数组包含索引 1 处的函数名和索引 2 处的参数。

    所以你会这样做:

    $orderid = call_user_func($matches[1], $matches[2]);
    

    如果值来自不受信任的来源,您显然需要非常小心。

    【讨论】:

    • 好的。那么为什么投反对票呢?这是一个完全合理的答案。
    • 我如何提取它..请举例
    • $matches[1] 和 $matches[2] 作为数组返回。
    • @user622378 已更新。我不是有意使用preg_match_all(),而是preg_match()
    【解决方案2】:

    不好的方法是使用eval() 函数。这在您的用例中非常很糟糕,因为 API 很可能会返回您不想执行的内容。

    这样做的好方法是解析您的字符串,验证其内容,并相应地映射调用及其参数。

    您可以使用正则表达式解析返回字符串:

    preg_match("/^(.+?)\((.*?)\)$/", $answer, $match);
    var_dump($match[1]); // method
    var_dump(explode(',', $match[2])); // arguments
    

    必须清理/验证上述内容。

    【讨论】:

      【解决方案3】:

      这样调用 call_user_func:

      $orderid = call_user_func('transaction', 123);
      

      另外,看看http://es.php.net/manual/en/function.call-user-func.php

      【讨论】:

      • 我知道这一点,但我需要获取 123 的值或参数来执行此操作。
      • @user622378:看你的代码,你好像不知道这个。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      相关资源
      最近更新 更多