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条)

报告相同问题?

悬赏问题

  • ¥15 爬虫爬取网站的一些信息
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件
  • ¥15 K8S部署二进制集群过程中calico一直报错