Hi Guys,

I'm having a problem with the below code. It's probably a simple mistake as I'm relatively new to PHP, and even newer to socket programming.

The background is that I'm developing a socket server for a multiplayer game. Here is the relevant code:

class PlayerList {

var $plist = array();

    public function addPlayer (Player $x) {
        $plist[] = $x;
        echo "players added. total: ".count($plist);
    }
    
    public function removePlayerNick ($x) {
        
        foreach ($plist as $k => $thePlayer) {
            
            if ($thePlayer->getNick() == $x) {
                unset ($plist[$k]);
            }                
            
        }
        $plist = array_values ($plist);
        
    }
    
    public function removePlayer ($i) {
        
        unset ($plist[$i]);
        $plist = array_values ($plist);
        
    }
    
    public function getNumPlayers () {
    
        return count($plist);
        
    }
    
    public function getPlayer ($i) {
        return $plist[$i];
    }
    
    public function message (String $m, String $n) {
        
        foreach ($plist as $k => $thePlayer) {
            
            socket_write($thePlayer->getSocket(), "/msg ".$n." ".$m);
            
        }
    
    }


}

The call to this class goes as follows:

$sock = socket_accept($socket);
                echo "sock: ".$sock;
                $p = new Player($sock);
                
                $i = $allPlayers->addPlayer($p);
                echo "numplayers: ".$allPlayers->getNumPlayers();

Now what I want to do is to add the newly created Player $p to the array $allPlayers. But that is not what happens. The output is as follows:

sock: Resource id #5
players added.
total: 1
numplayers: 0

The 'total:1' is to prove that the player IS being added to the array, however in the very next line, I ask the object to return its size, and it returns 0!

As I said, I presume it's something simple, but I've spent a while on this now... long enough to justify posting this question!

Thanks in Advance for any help...

Since you're using class variables, you need to specify them using $this.

public function addPlayer (Player $x) {
    $this->plist[] = $x;
    echo "players added. total: ".count($this->plist);
}

Wow, excellent.

That solved the problem, thanks!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.