如何设置一次 API 键并将其保存在函数中?
How can I set an API key once and save it within a function?
我正在研究一些 类 和功能。这些函数从需要 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/key,但两者的想法几乎相同。
// 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);
}
}
我正在研究一些 类 和功能。这些函数从需要 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/key,但两者的想法几乎相同。
// 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);
}
}