dtr32221 2013-03-20 21:24
浏览 54
已采纳

函数中的php调用构造函数并初始化对象

I'm not familiar with php OOP and now I'm in some trouble. I'm developing my project in structured programming (not OOP) and I have included a class (made by someone else) and within my structured function I must initialize the class and do things. If you don't understand what I have typed here, please watch the code:

<?php
require __DIR__ . '/SourceQuery/SourceQuery.class.php';

function get_server_info($ip, $port){

    define( 'SQ_SERVER_ADDR', $ip );
    define( 'SQ_SERVER_PORT', $port );
    define( 'SQ_TIMEOUT',     5 );
    define( 'SQ_ENGINE',      SourceQuery :: GOLDSOURCE );

    $Query = new SourceQuery( );

    try
    {
        $Query->Connect( SQ_SERVER_ADDR, SQ_SERVER_PORT, SQ_TIMEOUT, SQ_ENGINE );

        $result = (array)$Query->GetInfo();

    }
    catch( Exception $e )
    {
        $result = array('Players' => 0, 'MaxPlayers' => 0);
    }

    $Query->Disconnect( );
    unset($Query);
    return array('players' => $result['Players'], 'max_players' => $result['MaxPlayers']);
}
?>

Basically I have created a function called get_server_info which constructs a SourceQuery object. I'm querying Counter-Strike servers for number of players and max players.

I don't know if this is correct programatically (mixing structured with OOP). I don't want to change code or create methods in the class, I want to use my function. I'm getting result for each call (get_server_info()), but the problem is every result is same !

For example:

for($i = 0; $i < 30; $i++){
   $result = get_server_info('66.55.44.3'.$i, 27015);
   echo $result['players'].' - '.$result['max_players'].'<br />';
}

The result is the same for any server ! (Yes, they are all up and running). When I'm checking the servers on my server viewer program they have different number of players, but my result from this loop is the same ! I don't know why.

If I query manually one by one I'm getting the correct result.

I think it's because the object isn't deleted or .... I don't know.

  • 写回答

2条回答 默认 最新

  • duandongji2231 2013-03-20 21:33
    关注

    I think it's because you're trying to overwrite a constant. (define)

    Define the constants somewhere in your code outside any function and pass $id and $port directly to the class. And where do you have $Query initialized?

    Try:

    define( 'SQ_TIMEOUT',     5 );
    define( 'SQ_ENGINE',      SourceQuery :: GOLDSOURCE );
    
    function get_server_info($ip, $port){
    
        try
        {
            $Query->Connect( $ip, $port, SQ_TIMEOUT, SQ_ENGINE );
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料