PHP简单JSON-RPC
我正在尝试创建JSON-RPC HTTP服务。我使用的是POST方法 rest.phpPHP简单JSON-RPC,php,rest,Php,Rest,我正在尝试创建JSON-RPC HTTP服务。我使用的是POST方法 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 }
<?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
<?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;
}
现在我正在尝试实现更多的方法,这样我就可以像这样使用输入:
{
"method":"add",
"params": {
"num1": 15,
"num2": 10
}
}
因此,我向rest.php添加了函数:
public function add($n1, $n2) {
return $n1 + $n2;
}
问:如何确定调用的方法并在rest.php中使用新输入执行它
编辑:
{"num": 10 }
20
<?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;
}
您可以使用and(根据需要)来检查您获得的字符串是否与现有元素匹配
然后,您可以使用或执行该函数
例如:
<?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);
}
将我的测试添加到原始帖子中