如何在php中使用类

时间:2016-02-18 19:06:29

标签: php

我有这个php类,我不知道如何使用它。我知道一点点PHP,但我不知道如何使用/调用一个类。

<?php


Class Checkserver {
   static function getString(&$packet){
      $str = "";
      $n = strlen($packet);
      for($i=0;($packet[$i]!=chr(0)) && ($i < $n);++$i)
         $str .= $packet[$i];
      $packet = substr($packet, strlen($str));
      return trim($str);
   }
   static function getChar(&$packet){
      $char = $packet[0];
      $packet = substr($packet, 1);
      return $char;
   }
    function serverInfo($server) {
      list($ip,$port) = explode(":", $server);
      $fp = @fsockopen('udp://'.$ip, $port);
      if($fp) {
         stream_set_timeout($fp, 2);
         fwrite($fp,"\xFF\xFF\xFF\xFFTSource Engine Query\0\r");
         $temp = fread($fp, 4);
         $status = socket_get_status($fp); 
         if($status['unread_bytes']>0) {
            $temp = fread($fp, $status['unread_bytes']);
            $version = ord(self::getChar($temp));
            $array = array();
            $array['status'] = "1";
            if($version == 109) {
               $array['ip'] = self::getString($temp);
               $temp = substr($temp, 1);
               $array['hostname'] = self::getString($temp);
               $temp = substr($temp, 1);
               $array['mapname'] = self::getString($temp);
               $temp = substr($temp, 1);
               self::getString($temp);
               $temp = substr($temp, 1);
               self::getString($temp);
               $temp = substr($temp, 1);
               $array['players'] = ord(self::getChar($temp));
               $array['maxplayers'] = ord(self::getChar($temp));
            } elseif($version == 73) {
               self::getChar($temp);
               $array['hostname'] = self::getString($temp);
               $temp = substr($temp, 1);
               $array['mapname'] = self::getString($temp);
               $temp = substr($temp, 1);
               self::getString($temp);
               $temp = substr($temp, 1);
               self::getString($temp);
               $temp = substr($temp, 3);
               $array['players'] = ord(self::getChar($temp));
               $array['maxplayers'] = ord(self::getChar($temp));
            }
         } else {
            $array['hostname'] = 'Server offline';
            $array['mapname'] = '-';
            $array['players'] = '0';
            $array['maxplayers'] = '0';
            $array['status'] = '0';
         }            
      }
      return $array;


   }


}

?>

我试图通过在类所在的同一文件中写入来查询服务器:

<?php

   $newServer = serverInfo();
   $date = $newServer->serverInfo("127.0.0.1:27015");
?>

但我无法让它发挥作用。如何使用udp查询服务器,使用此类并打印输出?

1 个答案:

答案 0 :(得分:0)

serverInfo属于该类,因此您需要先创建该类的新实例,然后才能使用它。

$newServer = new Checkserver();
$date = $newServer->serverInfo("127.0.0.1:27015");