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
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测