在PHP服务器内,互相调用的方法有以下几种:
示例:
// 被调用文件:functions.php
function add($a, $b) {
return $a + $b;
}
// 调用文件:index.php
include 'functions.php';
$result = add(2, 3);
echo $result; // 输出 5
示例:
// 调用文件:index.php
$apiUrl = 'http://example.com/api';
$data = array('name' => 'John', 'age' => 30);
$options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$response = file_get_contents($apiUrl, false, $context);
$result = json_decode($response, true);
echo $result['message'];
示例(使用gRPC):
// 定义.proto文件
syntax = "proto3";
package example;
service Calculator {
rpc Add(AddRequest) returns (AddResponse) {}
}
message AddRequest {
int32 a = 1;
int32 b = 2;
}
message AddResponse {
int32 result = 1;
}
// 生成PHP代码
$ protoc --php_out=. example.proto
// 在调用文件中使用生成的代码
require 'vendor/autoload.php';
$client = new Example\CalculatorClient('localhost:50051', [
'credentials' => Grpc\ChannelCredentials::createInsecure(),
]);
$request = new Example\AddRequest();
$request->setA(2);
$request->setB(3);
$response = $client->Add($request);
$result = $response->getResult();
echo $result; // 输出 5
这些方法可以根据具体的需求和环境来选择使用。