我有以下代码以Wordpress插件页面的形式连接到AWS PHP SDK。尝试在最后一个函数(Call to a member function on a non-object
)中使用$MTurk
变量时,我收到bz_page_file_path
错误。我尝试过各种各样的解决方案,比如$ global变量,但没有运气。我还确认,如果我将bz_page_file_path
的内容移动到构造函数中,代码确实有效(因此它似乎可能是某种范围问题)。我该怎么做才能正确地将其传递给函数?
<?php
class BZ_NamePicker {
// Constructor
function __construct() {
require_once dirname(__FILE__) . '/aws-autoloader.php';
$MTurk = new Aws\MTurk\MTurkClient([
...
]);
add_action( 'admin_menu', array( $this, 'bz_add_menu' ));
}
/* Action to load admin menu */
function bz_add_menu() {
add_menu_page('NamePicker', 'NamePicker', 'manage_options', 'namepicker-dashboard',
array(__CLASS__, 'bz_page_file_path'),
'dashicons-sticky','3');
}
/* Action to load content on admin webpage */
function bz_page_file_path() {
$accountBalance = $MTurk->getAccountBalance([]);
echo $accountBalance['AvailableBalance'];
}
}
new BZ_NamePicker();
答案 0 :(得分:1)
<?php
class BZ_NamePicker {
// Constructor
function __construct() {
global $MTurk;
require_once dirname(__FILE__) . '/aws-autoloader.php';
$MTurk = new Aws\MTurk\MTurkClient([
...
]);
add_action( 'admin_menu', array( $this, 'bz_add_menu' ));
}
/* Action to load admin menu */
function bz_add_menu() {
add_menu_page('NamePicker', 'NamePicker', 'manage_options', 'namepicker-dashboard',
array(__CLASS__, 'bz_page_file_path'),
'dashicons-sticky','3');
}
/* Action to load content on admin webpage */
function bz_page_file_path() {
global $MTurk;
$accountBalance = $MTurk->getAccountBalance([]);
echo $accountBalance['AvailableBalance'];
}
}
new BZ_NamePicker();
您需要在要访问它的函数中调用该类作为全局对象