Support » Fixing WordPress » Problem in category

  • armstrong1118


    I am trying to declare a global variable in my category.php

    The code im using is
    <?php global $myVar = 16; ?>

    I tried to set it without the ‘global’ and it appears to work, but with the ‘global’ I just get a white screen with absolutely nothing….Am I doing something wrong?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator Samuel Wood (Otto)

    (@otto42) Admin

    Yes, that’s not how global variables work in PHP.

    You can do this to be certain:

    global $myVar;
    $myVar = 16;

    But generally speaking, you don’t have to explicitly define that you’re using a global unless you’re inside a function. Functions get their own local variables, they have to declare a variable to be global to access the global variable space instead of their local variable space.

    Read this, it’s useful info to know:

    Also note that you’re not *declaring* a variable. PHP does not require, nor have, variable declaration. It creates variables when you reference them. The global keyword just says that references to the variable given are references to that variable in the global scope, not in a local scope.



    if I declare a variable to be global in a function, should I be able to access it in any of my Pages?

    Moderator Samuel Wood (Otto)

    (@otto42) Admin

    Errr… what? I think you have misunderstood. You declare it global where you actually use it, so if you call the global in your Page code, then yeah, you can use it there.

    The term “global” doesn’t apply to the variable, it applies to the function that the variable is used in. It makes the references to the named variables into references to the global ones.

    Again, read this: . Read the examples. This is not the way most other programming languages work.

    In short, if you want to access a global variable in your Page, then you probably need to do just what I posted above: move the variable reference into global scope, then use it. Or use the $_GLOBALS superglobal. Either way.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Problem in category’ is closed to new replies.