使用两个相同的功能(不能重新声明类)

时间:2012-12-14 13:09:35

标签: php

  

可能重复:
  Reference - What does this error mean in PHP?

在下面的代码中,我创建了两个需要相同信息的函数。我正在使用this script

<?php 
function get_cbMain_Query() {
  define( 'Main_SERVER_ADDR', 'ip');
  define( 'Main_SERVER_PORT', 25565);
  define( 'Main_TIMEOUT', 1 );

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

  // Display everything in browser, because some people can't look in logs for errors
  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;
}

function get_cbTekkit_Query() {
  define( 'Tekkit_SERVER_ADDR', 'ip');
  define( 'Tekkit_SERVER_PORT', 25565);
  define( 'Tekkit_TIMEOUT', 1 );

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

  // Display everything in browser, because some people can't look in logs for errors
  Error_Reporting( E_ALL | E_STRICT );
  Ini_Set( 'display_errors', true );

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

  try
  {
    $Query->Connect( Tekkit_SERVER_ADDR, Tekkit_SERVER_PORT, Tekkit_TIMEOUT );
  }
  catch( MinecraftQueryException $e )
  {
    $Error = $e->getMessage();
   echo 'error. <br>'. $Error;
  }
  return $Query;
}

使用此脚本并执行以下操作时(从其他页面,此脚本包含在另一页中)

          $cbMain = get_cbMain_Query();
          $cbTekkit = get_cbTekkit_Query();

然后我得到:

 Cannot redeclare class MinecraftQueryException in MinecraftQuery.class.php on line 5

我是PHP中的类广告对象的新手,无法弄清楚为什么我不能同时调用两个函数并使用它们。请帮忙吗?

2 个答案:

答案 0 :(得分:3)

更改两个功能中的行

require __DIR__ . '/mcQuery/MinecraftQuery.class.php';

阅读

require_once __DIR__ . '/mcQuery/MinecraftQuery.class.php';

这将确保文件包含一次,并避免错误。

答案 1 :(得分:0)

您可以require_onceinclude_once,也可以输入

if(!function_exists('get_cbMain_Query')){... }
if(!function_exists('get_cbTekkit_Query')){... }

围绕每个函数确保它们只被声明一次。