[英]How can I make this code into a class so I can reuse it?
I am using xPaw's Minecraft Query: https://github.com/xPaw/PHP-Minecraft-Query 我正在使用xPaw的Minecraft查询: https : //github.com/xPaw/PHP-Minecraft-Query
I made a function to it so I can connect to our servers, however the problem is that we have multiple servers, so I have to copy and paste the function and rename the function and other parts of the code so it can connect to the other servers. 我为其创建了一个函数,以便可以连接到我们的服务器,但是问题是我们有多个服务器,因此我必须复制并粘贴该函数,并重命名该函数和代码的其他部分,以便它可以连接到另一个服务器。
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;
}
I'd like to pass an array to the class and call it 我想将数组传递给类并调用它
$mcQuery = new mcQuery();
// Define servers
$server = [
'1server' => '1.server.com',
'2server' => '2.server.com',
'3server' => '3.server.com',
'4server' => '4.server.com'
];
Calling it would look like this: 调用它看起来像这样:
Status: <?php echo $mcQuery->getStatus($server['1server']); ?>
I'm not sure how to get around into doing this though. 我不确定如何解决这个问题。 How can I get something like that? 我如何得到这样的东西?
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 ... */
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.