Trying to get logged-in user data inside php class

Once you said is you first time using OOP, I want to say: stop using & before $this: PHP4 died long time ago.

Second tip, don’t use global variables, if you can. I know that function like wp_get_current_user use global variable internally, but I hope that in future it will not be so anymore, however not seeing that global word in my code, make me fill a little better.

Third tip, try to make your plguin more solid using type hinting.

Here I post how I had wrote that code.

Firts of all I’d wrote 2 classes, probably in 2 different files named in same way of class:

class WP_PM_User extends WP_User {

  function getID() {
    return $this->ID;
  }

}

class WP_PM {

  protected $user;

  function __construct ( WP_PM_User $user = NULL) {
    if ( ! is_null( $user ) && $user->exists() ) $this->user = $user;
  }

  function getUser() {
    return $this->user;
  }

}

After that, somewhere in plugin (maybe in main plugin file) I’d write two function like this:

function getWPPM() {

  if ( ! did_action('wp_loaded') ) {
    $msg = 'Please call getCurrentUser after wp_loaded is fired.';
    return new WP_Error( 'to_early_for_user', $msg );
  }

  static $wp_pm = NULL;

  if ( is_null( $wp_pm ) ) {
    $wp_pm = new WP_PM( new WP_PM_User( get_current_user_id() ) );
  }

  return $wp_pm;
}


function getCurrentUser() {

  $wppm = getWPPM();

  if ( is_wp_error( $wppm ) ) return $wppm;

  $user = $wppm->getUser();

  if ( $user instanceof WP_PM_User ) return $user;
}

add_action( 'wp_loaded', 'getCurrentUser' );

Doing so, everywhere in your plugin you can call getCurrentUser and retrieve the current user object, and if you want the ID, you can call getID() on the user returned by getCurrentUser.

Usage example:

add_action( 'wp_loaded', function() {

  $current_user = getCurrentUser();
  if ( $current_user instanceof WP_PM_User ) {
    echo 'Current user ID: ' . $current_user->getID();
  } else {
    echo 'No one logged in';
  }

}, 30 );

Leave a Comment