全局变量在函数内部不起作用

时间:2017-09-13 16:52:31

标签: php wordpress global-variables

在wordpress插件中我有这段代码

 $country_table = $wpdb->prefix . "trackbyid_country";
 $cities_table  = $wpdb->prefix . "trackbyid_cities";
 function database_creation(){
    global $wpdb;
    global $country_table;
    global $cities_table;
    $AO_name = "trackbyid_dbv";
    $AO_value = "1";
    add_option($AO_name, $AO_value);

    $charset_collate = $wpdb->get_charset_collate();
    $sql = "CREATE TABLE $country_table (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        country tinytext NOT NULL,
        PRIMARY KEY  (id)
        ) $charset_collate;";
    require_once ( ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    $sql = "CREATE TABLE $cities_table(
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
        city tinytext NOT NULL,
        country_id mediumint(9) NOT NULL,
        city_latitude mediumint(9) NOT NULL,
        city_longitude mediumint(9) NOT NULL,
        PRIMARY KEY  (id)
        ) $charset_collate;";
     dbDelta($sql);


 }

我认为我的问题(数据库未创建)是使用全局$ country_table和$ cities_table变量。当我把变量变成局部时,问题就解决了! 我的全局变量声明和用法有什么问题?

1 个答案:

答案 0 :(得分:0)

您的变量$country_table$cities_table将不会被定义,因为在您尝试在这些变量中使用它之前,您没有引入全局$ wpdb。试试这个:

global $wpdb;
$country_table = $wpdb->prefix . "trackbyid_country";
$cities_table  = $wpdb->prefix . "trackbyid_cities";

function database_creation(){
    global $country_table, $cities_table;

    ...

}