WordPress.org

Ready to get started?Download WordPress

Forums

(Global) variable issue (3 posts)

  1. thomasgericke
    Member
    Posted 4 years ago #

    I have an issue concerning (global?) variables. Some pseudo code:

    function my_plugin_install() {
            // glad, we have nothing to do here...
    }
    
    add_action ('my_plugin/my_plugin.php', 'my_plugin_install');
    
    global $my_var;
    $my_var = "";
    
    function my_function() {
            global $my_var;
            $my_var = "true";
            return $my_var;
    }
    
    add_filter ('some_foreign_call_from_another_plugin', 'my_function');
    
    function write2header() {
            global $my_var;
            echo "Within our header: " . $my_var;
    }
    
    add_action ('admin_head', 'write2header');

    What do I want to do?

    My plugin is called by some_foreign_call_from_another_plugin's filter hook and I immediately call my_function. That works well. Within that function, I set the variable $my_var to "true". That variable is defined as global earlier.

    Later in my plugin, I want to insert some code into the <HEAD> part of the output. And I want to use $my_var there.

    But that's the one thing, that doesn't work. Within the header, it says: "Within our header: " - but nothing more. No output of $my_var.

    Why? What am I doing wrong?

    Do I have to define my global variable later? Earlier? Where?

    Should I use $GLOBALS["my_var"]? I already tried a little bit with that - didn't work either. :-(

    Thomas

  2. thomasgericke
    Member
    Posted 4 years ago #

    BTW: this one totally works in a plain PHP file (without WordPress):

    Hello World!<BR />
    <?PHP
    
            echo "Before 1st function: " . $my_var . "<BR />";
    
            function my_function() {
                    global $my_var;
                    $my_var = "true";
                    return $my_var;
    
            }
    
            echo "After 2st function: " . my_function() . "<BR />";
    
            function my_2nd_function() {
                    global $my_var;
                    echo "In 2nd function: " . $my_var . "<BR />";
            }
    
            my_2nd_function();
    
    ?>

    When calling the PHP file in a browser, output is:

    Hello World!
    Before 1st function:
    After 2st function: true
    In 2nd function: true

    So, it must be a WordPress issue. Can someone help, please?

    Thomas

  3. andykassabian
    Member
    Posted 4 years ago #

    I've got exactly the same problem, anyone got a solution?

Topic Closed

This topic has been closed to new replies.

About this Topic