在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
這些方法可以根據具體的需求和環境來選擇使用。