An alternative to globals

I have a set of variables that should be available on my site. Although I could declare them in my header.php file, I would prefer to define them in functions.php or just not in the template file (view). All that I read says DO NOT USE GLOBAL ... excellent. But what is the best way to define these variables?

Here is what I want to determine:

 global $favorites_array;
 global $user;
 global $user_id;
 global $user_name;
 global $uri;

 $user = wp_get_current_user();
 $user_name = $user->user_login;
 $user_id = $user->ID;
 $user_id = get_current_user_id();
 $uri = $_SERVER['REQUEST_URI'];
+4
source share
3 answers

, ( , ), , , , , . .

WordPress , , wp_get_current_user() , $current_user.

wp_get_current_user() , $current_user :

if ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->ID ) )
    return $current_user;

, , , - . , . WordPress wp_get_current_user(), , global $user , . , , , :

// Can't do this:
echo "The user is {wp_get_current_user()->user_login}";

... , , .

function your_func() {
  $login = wp_get_current_user()->user_login;
  echo "The user is $login";
}

$user_id, ID -, ID -, . :

echo $user_id;

:

echo wp_get_current_user()->ID;
// or even better, using the API function
echo wp_get_current_user_id();

, $_SERVER, PHP, - , :

$uri = $_SERVER['REQUEST_URI'];

$_SERVER['REQUEST_URI'] . , , , :

function uses_uri() {
  $uri = $_SERVER['REQUEST_URI'];
  echo "I like to say $uri over and over $uri $uri $uri";
}

, , , , ( , , , ).

API WordPress, , API- URI-. , WP-.

+4

, . - .

singleton , , , , .

functions.php:

class My_Theme {
    public $favorites_array;
    public $user;
    public $user_id;
    public $user_name;
    public $uri;

    protected function __construct(){
        // TODO: put all your add_filter and add_action calls here  

        $this->favorites_array = array();
        $this->user = wp_get_current_user();
        $this->user_name = $this->user->user_login;
        $this->user_id = get_current_user_id();
        $this->uri = $_SERVER['REQUEST_URI']; 
    }

    function get_instance() {
        static $instance;
        if( ! isset( $instance ) )
            $instance = new self();

        return $instance;
    }
}

My_Theme::get_instance();

header.php :

<?php
    $my_theme = My_Theme::get_instance();
?>
<html>
    ...
    ...
    <title>Hello <?php echo( esc_html( $my_theme->user_name ) ); ?></title>

, , , , , $favorites_array, WordPress .

+2

, , : " ", . "". . "", , , wuth global, ( ) ( C dev 100 ). PHP .

, , , , var . , "gl" "glb", . "" . , fucntion global .. . .

, , , (DEFINE) .

+1

All Articles