我目前正在为客户构建一个Wordpress插件,我遇到了访问函数内部函数外部创建的变量和对象的一些问题。例如,这是我的代码:
// Include files:
require_once('classes/panel.inc.php');
$panel = new AdminPanel();
// Actions & Options:
add_action('admin_menu', 'configurePages');
// Configure pages:
function configurePages(){
// Boats:
add_menu_page(__('Båtar','admin-main'), __('Båtar','boats'), 'manage_options', 'boats', array($panel, 'displayBoatManager'));
add_submenu_page('boats', __('Sök båtar','search-boats'), __('Sök objekt','search-boats'), 'manage_options', 'search-boats', array($panel, 'displayBoatSearch'));
add_submenu_page('boats', __('Hantera utrustning','manage-equipment'), __('Hantera utrustning','manage-equipment'), 'manage_options', 'manage-equipment', array($panel, 'displayEquipmentManager'));
// Customers:
add_menu_page(__('Kunder','admin-main'), __('Kunder','boats'), 'manage_options', 'customers', array($panel, 'displayCustomerManager'));
add_submenu_page('customers', __('Sök kunder','search-customers'), __('Sök kunder','search-customers'), 'manage_options', 'search-customers', array($panel, 'displayCustomerSearch'));
}
正如您所看到的,我已经创建了一个面板对象,如果我在函数之前转储内容,我会得到正确的输出。但是,所有页面都抱怨面板不是有效变量,也不是对象。可能导致这种情况的原因是什么?
我可以通过简单的添加来解决它:
require_once('classes/panel.inc.php');
$panel = new AdminPanel();
在configurePages函数内部。但我不应该这样做。 我有与include相同的问题,它们很简单,不会在函数内部被识别。如果有人能够在这个问题上分享一些见解并且可能如何解决它,我将非常高兴。
提前致谢! // 乔纳森
答案 0 :(得分:1)
您无法从函数中访问$panel
,因为您的函数在其本地范围内查找变量$panel
,而实际上已在全局范围内定义。
在函数中使变量可用的一种方法是
function configurePages() {
global $panel;
…
}
有关变量范围的更多信息,请访问:http://php.net/manual/en/language.variables.scope.php