0
votes

I'm doing a project using HTML5 WebSockets, with a PHP server using a websockets library right here at Github.

My project also depends on knowing how many players are online. The library has three abstract methods, connected, closed, and process. In connected and closed, it takes a parameter $user, which is a custom class that has a random alphanumeric string as the variable id.

I have a protected $users = []; at the beginning of my class, inside my class, which extends the WebSocketServer that the library provides. In my connected method, I array_push the $user provided to the $users array. Then, in my closed method, I loop through the $users array, checking if the element in $users has the same $id as the $user provided, and then array_splicing that element away if that is try.

So. Here's my problem. When I run my PvPASCIIServer.php as root, and connect using a test web page, everything works fine. BUT, when I disconnect, it says:

PHP Warning:  array_splice() expects parameter 1 to be array, null given in /var/www/PvPASCII/PvPASCIIServer.php on line 24

Shouldn't array() not initialize $users as null? Why would it? I've also tried using the literal format of initializing arrays, [], but even that didn't work. And even wierder, my array_push at the beginning of my connected function did not return an error message. Logically, it should have worked and pushed a $user to the end of the $users array, so even if it was initialized null, it should have not been null after that.



My code, if you need it:

#!/usr/local/bin/php
<?
require_once("websockets.php");

class PvPASCIIServer extends WebSocketServer
{
    protected $users = [];

    protected function connected($user)
    {
        $this->send($user, "say Pong!");
        array_push($this->users, $user);
        echo $user->id;
        return true;
    }

    protected function closed($user)
    {
        echo "Client " + $user->id + " disconnected from the server.";
        for($i = 0; $i < sizeof($this->users); $i++)
        {
            if($this->users[$i]->id == $user->id)
            {
                array_splice($users, $i, 1); // <--  Line with the error
            }
        }
    }

    protected function process($user, $message)
    {
        // Yet to be determined.
    }
}

$host = "localhost";
$port = 3000;

$server = new PvPASCIIServer($host, $port);
$server->run();
?>
2

2 Answers

4
votes

$users needs to be $this->users just like everywhere else in your class:

if($this->users[$i]->id == $user->id)
{
     array_splice($this->users, $i, 1); // <--  Line with the error
}
2
votes
array_splice($users, $i, 1); // <--  Line with the error

Should be:

array_splice($this->users, $i, 1); // <--  Line with the error

Since you want to use the class variable $users and not the function variable $users

EDIT:
What John Conde also says (he was a little faster with typing ;-) )