WordPress.org

Ready to get started?Download WordPress

Forums

Problem in category (4 posts)

  1. armstrong1118
    Member
    Posted 6 years ago #

    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?

  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    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:
    http://php.net/global

    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.

  3. armstrong1118
    Member
    Posted 6 years ago #

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

  4. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    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: http://php.net/global . 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.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.