如何将此代码转换为类,以便重用它?

时间:2014-04-11 15:34:31

标签: php

我正在使用xPaw的Minecraft查询: https://github.com/xPaw/PHP-Minecraft-Query

我为它做了一个函数,所以我可以连接到我们的服务器,但问题是我们有多个服务器,所以我必须复制并粘贴函数并重命名函数和代码的其他部分,以便它可以连接到其他服务器。

function get_MQ_Query() {
  define( 'MQ_SERVER_ADDR', '1stserver.com' );
  define( 'MQ_SERVER_PORT', 25565 );
  define( 'MQ_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( MQ_SERVER_ADDR, MQ_SERVER_PORT, MQ_TIMEOUT );
  }
  catch( MinecraftQueryException $e )
  {
    $Error = $e->getMessage();
   echo 'error. <br>'. $Error;
  }
  return $Query;
}

我想将一个数组传递给类并调用它

$mcQuery = new mcQuery();
// Define servers
$server = [
    '1server' => '1.server.com',
    '2server' => '2.server.com',
    '3server' => '3.server.com',
    '4server' => '4.server.com'
];

调用它看起来像这样:

Status: <?php echo $mcQuery->getStatus($server['1server']); ?>

我不知道如何绕过这样做。我怎么能得到这样的东西?

2 个答案:

答案 0 :(得分:1)

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

class YourClass {
    protected $_query;

    public function __construct($host, $port, $timeout=1) {
        $Timer = MicroTime( true );
        $Query = new MinecraftQuery( );
        try {
            $Query->Connect( $host, $port, $timeout );
        } catch( MinecraftQueryException $e ) {
            $Error = $e->getMessage();
            echo 'error. <br>'. $Error;
        }
        $this->_query = $Query;        
    }

    public function getPlayers() {/*...*/}

    public function getVersion() {/*...*/}

} 

$connect = new YourClass('1.server.com', 25564);

/* etc ... */

答案 1 :(得分:1)

    require __DIR__ . '/mcQuery/MinecraftQuery.class.php';
class MyMcQuery
{
    protected $port;
    protected $timeout;

    public function __construct()
    {
    $this->port = 25565;
    $this->timeout = 1;
    }

    public function query( $server )
    {          
      $Timer = MicroTime( true );
      $Query = new MinecraftQuery( );

      try
      {
        $Query->Connect( $server, $this->port, $this->timeout );
      }
      catch( MinecraftQueryException $e )
      {
        $Error = $e->getMessage();
       echo 'error. <br>'. $Error;
      }
      return $Query;
    }    
}