Create and use global variable without the 'global' keyword?

拈花ヽ惹草 提交于 2019-12-24 13:35:37

问题


As of now I create a variable like this in a file that's loaded on all pages:

<?php

  add_action( 'parse_query', 'my_global_vars' );
  function my_global_vars() {

    /* CUSTOM GLOBAL VARIABLES */
    $variable_name = get_query_var('category_name');

  }

?>

And every time I want to use it (in other files), I must do it like this:

<?php

  global $variable_name;

  if( $variable_name = 'news' ){

    // Do something

  }

?>

And when I need to use the variable multiple times in the same file, I add global $variable_name; at the top of the file, and simply use $variable_name in rest of the instances.

But as the number of variables increase, I find it harder to manage the list of global $variable_names at the top of all files.

Is there a way to define a variable as global at the time of creation and simply use $variable_name everywhere else?

EDIT: One way is to define variable like this:

<?php

  add_action( 'parse_query', 'my_global_vars' );
  function my_global_vars() {

    /* CUSTOM GLOBAL VARIABLES */
    global $variable_name;
    $variable_name = get_query_var('category_name');

  }

?>

And use it like using $GLOBALS[] like this $GLOBALS['variable_name'] elsewhere.


回答1:


Having a lot of global vars is usually bad. It becomes a mess very quickly.

If you really need global variables the best approach is to use static class variables. They are just as global as the others, but they enforce better naming and pre-declaration so the end result is somewhat better.

If you really need normal global vars you can also use the $GLOBALS variable, it is available in every scope and is basically an array of all the global variables.

global $variable_name;
do_something_with($variable_name);

is the same as

do_something_with($GLOBALS['variable_name']);



回答2:


You can use a static class for this and keep it OOP:

<?php
    class GlobalVariables {
        private static $vars = array();

        public static function get($name, $default = null) {
            return (isset(self::$vars[$name]) ? self::$vars[$name] : $default);
        }

        public static function set($name, $value) {
            self::$vars[$name] = $value;
        }
    }

    function foo() {
        GlobalVariables::set('foo', 'oof');
    }

    function bar() {
        var_dump( GlobalVariables::get('foo') );
    }

    foo();
    bar(); //oof
?>

DEMO


Alternatively, you can use a Singleton pattern:

<?php
    class GlobalVariables {
        private static $instance;

        private $vars = array();

        public static function get() {
            if (empty(self::$instance)) {
                self::$instance = new GlobalVariables();
            }
            return self::$instance;
        }

        public function __get($name) {
            return (isset($this->vars[$name]) ? $this->vars[$name] : null);
        }

        public function __set($name, $value) {
            $this->vars[$name] = $value;
        }
    }

    function foo() {
        GlobalVariables::get()->foo = 'oof';
    }

    function bar() {
        var_dump( GlobalVariables::get()->foo );
    }

    foo();
    bar(); //oof
?>

DEMO.

Use whichever you find most readable.

GlobalVariables::set('key', 'value');
GlobalVariables::get('key');

or

GlobalVariables::get()->key = 'value';
GlobalVariables::get()->key;

Completely alternatively, if you hate dynamicness, simply use static variables (this, however, requires you to create all variables beforehand):

<?php
    class GlobalVariables {
        public static $foo;
    }

    GlobalVariables::$foo = 'oof';

    var_dump( GlobalVariables::$foo );
?>



回答3:


Using global outside a function doesn't do anything. It's meant for inside functions. You can simply remove your global statements.

Edit: I suggest that you try to reduce the number of global variables you have by structuring them. Group them into arrays or objects. E.g., instead of user_name, user_id, user_is_admin, prefer user['name'], user['id'], user['is_admin'], then you only have one variable (user) to declare as global instead of three.



来源:https://stackoverflow.com/questions/19934727/create-and-use-global-variable-without-the-global-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!