Is it possible to dynamically reload PHP code while script is running?

Simon Forsberg picture Simon Forsberg · Jun 5, 2012 · Viewed 10.8k times · Source

I'm having a multiplayer server that's using PHPSockets, and thus is written entirely in PHP.

Currently, whenever I'm making any changes to the PHP server-script I have to kill the script and then start it over again. This means that any users online is disconnected (normally not a problem because there aren't so many at the moment).

Now I am rewriting the server-script to use custom PHP classes and sorten things up a little bit (you don't want to know how nasty it looks today). Today I was thinking: "Shouldn't it be possible to make changes to the php source without having to restart the whole script?".

For example, I'm planning on having a main.php file that is including user.php which contains the class MyUser and game.php which contains the class MyGame. Now let's say that I would like to make a change to user.php and "reload" the server so that the changes to user.php goes into effect, without disconnecting any online users?

I tried to find other questions that answered this, the closest I got is this question: Modifying a running script and having it reload without killing it (php) , which however doesn't seem to solve the disconnection of online users.

UPDATE

My own solutions to this were:

  1. At special occations, include the file external.php, which can access a few variables and use them however it'd like. When doing this, I had to make sure that there were no errors in the code as the whole server would crash if I tried accessing a method that did not exist.
  2. Rewrite the whole thing to Java, which gave me the possibility of adding a plugin system using dynamic class reloading. Works like a charm. Bye bye PHP.

Answer

webbiedave picture webbiedave · Jun 5, 2012

Shouldn't it be possible to make changes to the php source without having to restart the whole script?

[...]

I'm planning on having a main.php file that is including user.php which contains the class MyUser

In your case, you can't. Classes can only be defined once within a running script. You would need to restart the script to have those classes redefined.