Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

In front-page.php I have the following code:

<span class="amountOnline">
     Online:
     <?php echo $cbMain->GetInfo()['Players'] . '/' . $cbMain->GetInfo()['MaxPlayers']; ?>
</span>

Which is a function in functions.php that calls from this script.It works perfectly.

But once I move this code from front-page.php to header.php, I get the following error:'

Notice: Undefined variable: cbMain in C:\Users\...\header.php on line 102

Fatal error: Call to a member function GetInfo() on a non-object in C:\Users\...\header.php on line 102

In functions.php, I have this function for example:

function get_cbMain_Query() {
  define( 'Main_SERVER_ADDR', '0.0.0.0');
  define( 'Main_SERVER_PORT', 25565);
  define( 'Main_TIMEOUT', 1 );

  // require bloginfo('template_url') . 'inc/avatars/MinecraftQuery.class.php';
  require_once __DIR__ . '/includes/mcQuery/MinecraftQuery.class.php';

  Error_Reporting( E_ALL | E_STRICT );
  Ini_Set( 'display_errors', true );

  $Timer = MicroTime( true );
  $Query = new MinecraftQuery( );

  try
  {
    $Query->Connect( Main_SERVER_ADDR, Main_SERVER_PORT, Main_TIMEOUT );
  }
  catch( MinecraftQueryException $e )
  {
   // $Error = $e->getMessage();
   // echo 'error. <br>'. $Error;
  }
  return $Query;
}

Then

$cbMain = get_cbMain_Query();

So I can use functions in my static front-page.php file, but once I move this script to header.php, it does not work and gives an error. How do I fix this?

share|improve this question

2 Answers 2

Your class instance is not in the scope of header.php, you need global $cbMain before accessing member functions.

share|improve this answer

The content of your header.php is called with get_header(), so all variales inside of this file act in another scope than the calling file.

So either get the variable from the global scope or build a wrapper in your functions.php to access the object from anywhere:

function get_cbmain() 
{
    static $instance = NULL;

    NULL === $instance and $instance = new MinecraftQuery;

    return $instance;
}

Now you can get the object instance with:

get_cbmain()->GetInfo();
share|improve this answer
    
Thank you! It seemed to work, kinda. Look at my edit and see how I set the code up. I can't just use new MinecraftQuery because I use two of these same classes. –  devs Jan 22 '13 at 6:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.