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?
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
}
Well, first of all, you have a typo in your code assuming a variable called $playereNumber
. If this is not the issue, you can try following code for your class.
class PlayerList
{
public static $playerList = [];
function getPlayer($index)
{
return isset(static::$playerList[$index]) ? static::$playerList[$index] : null;
}
}
You should also consider not making the $playerList
static in case you will be loading them from some database later.
Try this code :
class PlayerList
{
public static $playerList = [];
function getPlayer($index)
{
return isset(static::$playerList[$index]) ? static::$playerList[$index] : null;
}
}
$players=new PlayerList();
$playerNumber=readline("
Enter player number:");
$player=$players->getPlayer($playerNumber);
if($player){
//player exist
}
else{
//player is null
}