我正在尝试创建JSON服务。我用的是邮政法。
rest.php
<?php
header('Content-Type: application/json');
$input = file_get_contents("php://input");
$json = json_decode($input);
$output = $json->num + 10;
echo json_encode($output);
?>输入:
{"num": 10 }输出:
20现在我正在尝试实现更多的方法,这样我就可以使用这样的输入:
{
"method":"add",
"params": {
"num1": 15,
"num2": 10
}
}因此,我向rest.php添加了函数
public function add($n1, $n2) {
return $n1 + $n2;
}问:如何确定调用的方法并使用新的输入在rest.php中执行?
编辑:
<?php
header('Content-Type: application/json');
$input = file_get_contents("php://input");
$json = json_decode($input);
foreach ($json->params as $param) {
$params[] = $param;
}
$output = call_user_func_array($json->method, $params);
echo json_encode($output);
function add($n1, $n2) {
return $n1 + $n2;
}发布于 2014-05-21 13:29:11
您可以使用存在和存在 (取决于您的需要)来检查您得到的字符串是否与现有元素匹配。
然后,可以使用功能或方法来执行函数。
例如:
<?php
class foo{
public function add($n1, $n2) {
return $n1 + $n2;
}
}
$method = "add";
$object = new foo();
$n1 = 1;
$n2 = 8;
if(method_exists($object, $method))
{
call_user_method($method, $object, $n1, $n2);
}编辑:在这个例子中,我分配了n1和n2参数硬编码的值。在您的示例中,您可以从JSON获得params数组,并将其作为参数提供给所有方法。这样,您就不必在方法主体之外测试接收到的参数。
https://stackoverflow.com/questions/23784540
复制相似问题