duandai7601 2016-09-02 14:32
浏览 14

当索引处的值是对象时,在PHP中处理未定义的偏移量警告

I have a code like this:

class PlayerList{
    public static $player_list= array();
    //other functions
    function getPlayer($playerNumber){

           if(isset((self::$player_list[$playerNumber])))
              return self::$player_list[$playerNumber];
            else
              return NULL;
      }

This function getPlayer($playerNumber) should return the player object in the static array $player_list indexed using the given $playerNumber. It works when the index exists else throws an undefined offset. The index is an important attribute of objects of Player class, so re-ordering the array is out of question.

Now, in the calling part:

$players=new PlayerList();
$playerNumber=readline("

Enter player number:");
$player=$players->getPlayer($playerNumber); 

if(//valid player){
//code
}
else{
//code
}

How do i check if the indexed player exists or not,and if not, return null, in the getPlayer function itself, and prevent PHP from giving undefined offset notice?

  • 写回答

3条回答 默认 最新

  • drll42469 2016-09-02 14:38
    关注

    As you are returning NULL when you cannot find a player, simply test for NULL using isset()

    $player=$players->getPlayer($playerNumber); 
    if ( isset($player) ) { 
        // Player exists
    }else{
        // Player Does NOT exists
    }
    

    In fact you could probably get away with a simple

    $player=$players->getPlayer($playerNumber); 
    if ( $player ) { 
        // Player exists
    }else{
        // Player Does NOT exists
    }
    
    评论

报告相同问题?