我正在研究一些类和函数。这些函数从需要 API 密钥的 API 中获取数据。是否可以设置一次 API 密钥,然后在整个程序中使用它?
// Class example
class Airport
{
public function setClient($appId, $appKey)
{
$client = new GuzzleHttp\Client([
'headers' => array(
'resourceversion' => 'v4',
'accept' => 'application/json',
'app_id' => $appId, // Set this
'app_key' => $appKey // And this
)
]);
}
}
// Other file example
require 'classes.php';
$airport = new Airport();
$airport->setClient('xxxxxxxxxxx', 'xxxxxxxx');
// Continue to use other functions without setting the API key again.
您可以使用将它们保存为属性 $this
我不确定您是要重用客户端还是应用程序 ID/密钥,但无论哪种方式,它的想法都差不多。
// Class example
class Airport
{
private $appId;
private $appKey;
private $client;
public function setClient($appId, $appKey)
{
$this->appId = $appId;
$this->appKey = $appKey;
$this->client = new GuzzleHttp\Client([
'headers' => array(
'resourceversion' => 'v4',
'accept' => 'application/json',
'app_id' => $this->appId, // Set this
'app_key' => $this->appKey // And this
)
]);
}
// New function that uses the client
public function someOtherMethod()
{
$x = $this->client->someMethod();
}
// new function that uses the app properties
public function anotherMethod()
{
$x = new Something($this->appId, $this->appKey);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句