can not call functions in function.php

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?

Topic functions static-website Wordpress

Category Web


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();

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

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.