Support » Plugin: Insert PHP Code Snippet » Need Global Scope of PHP Variables between snippets

  • Resolved dccharron


    I’ve been using Insert PHP plugin for many years.

    I use the old shortcode i.e. [insert_php]my PHP code[/insert_php]
    It’s been working perfectly but, given the threat of deprecation, I decided to try converting to “snippets”.

    In my first attempt I discovered a major difference in the way snippets work from the old shortcode.

    The problem relates to the scope of PHP variables. With the old shortcode, I was able to set up variables in one pair like this:

    [insert_php]$my_var=”Some Value”;[/insert_php]

    and then later reference those variables in another pair (within the same page) like this

    [insert_php]echo $my_var;[/insert_php]

    In fact, I could reference this variable in any number of pairs within the same page. The scope of my variables is global.

    This worked perfectly since I could do the complex work of setting the variables (they are set to different values depending on context and conditions) just once and then use the variables in a number of places without repeating the code.

    With snippets, variables appear to have a local scope. In other words, variables set in one snippet are not available in a subsequent snippet.

    So I seem to have the following choices:

    1- Revert to using the old shortcode.
    2- Repeat all the complex code that sets up the PHP variables in each of the snippets that references them.

    Is my understanding correct? Or is there some way to make snippets work in the same way as the old shortcode.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author f1logic


    hi there
    in order to get the variable across snippets in same page u can store them in php globals array like below
    Then you can access the same anywhere in same request

    Thank you for the solution.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.