plugins – Set and access global variable

Question

I am learning plugin dev and modified this example snippet. I don’t get why $myvar is empty in the my_plugin_action_handler function’s scope.

<?php
/**
 * Plugin Name: TEST Plugin
 */

global $myvar;
$myvar = false;



function myplugin_activate() {
    global $myvar;
    
    $myvar = true;
    error_log($myvar); // this will be 'whatever'
}

function my_plugin_action_handler(){
    global $myvar;
    if($myvar){
        error_log("Var true");
    }
}

register_activation_hook( __FILE__, 'myplugin_activate' );
add_action('admin_notices', 'my_plugin_action_handler');

in progress 0
DerWaldie 1 month 2021-06-16T15:56:05-05:00 0 Answer 0 views 0

Answer ( 1 )

    0
    2021-06-19T02:51:51-05:00

    Global variables in PHP are not persistent across requests. You need to store the value in the database if that’s what you need.

Leave an answer

Browse
Browse