我试图写一个插件,我试图定义一个API密钥,并启动一个新的类,我的其他函数可以使用。我希望这是发起所有的时间(即使我的插件已经注册)。我尝试了以下代码:
if ( !class_exists( 'Mailchimp' ) )
{
require_once 'src/Mailchimp.php';
}
function init() {
$apiKey = '1234';
$api = new Mailchimp( $apiKey );
}
然而,我有另一个函数,看起来像这样:
function rb_mailchimp_options() {
$types = array('user'=>true, 'base'=>true);
$filters = array('include_inactive'=>true, 'include_drag_and_drop'=>true);
$templates = $api->templates->getList($filters);
}
我得到一个错误消息,因为它说Call to a member function getList() on a non-object
,所以它不识别我之前试图初始化的$api
变量。如有任何建议,不胜感激。
如果您只想在该类中使用API,请将其存储在类变量
中protected $api;
function init() {
$apiKey = '1234';
$this->api = new Mailchimp( $apiKey );
}
function rb_mailchimp_options() {
$types = array('user'=>true, 'base'=>true);
$filters = array('include_inactive'=>true, 'include_drag_and_drop'=>true);
$templates = $this->api->templates->getList($filters);
}
查看添加的$this->api
来访问类中的类变量。
如果你想在你的类之外使用它,你应该创建一个getter。
对你的编辑:
如果你在一个类中没有这些函数,但它们像这样一起工作,你应该考虑将它们组合在一个类中,以便更容易地管理它们。
如果您不想这样做,最简单的方法是使用$api
作为参数:
function init() {
$apiKey = '1234';
return new Mailchimp( $apiKey );
}
function rb_mailchimp_options($api) {
$types = array('user'=>true, 'base'=>true);
$filters = array('include_inactive'=>true, 'include_drag_and_drop'=>true);
$templates = $api->templates->getList($filters);
}
,然后像这样调用它们:
$api = init();
rb_mailchimp_options($api);