How to implement event listening in PHP

后端 未结 5 909
天命终不由人
天命终不由人 2020-12-08 12:22

here is my problem: I have a script (let\'s call it comet.php) whic is requsted by an AJAX client script and wait for a change to happen like this:

while(no         


        
5条回答
  •  独厮守ぢ
    2020-12-08 13:01

    It really depends on what you are doing in your server side script. There are some situations in which your have no option but to do what you are doing above.

    However, if you are doing something which involves a call to a function that will block until something happens, you can use this to avoid racing instead of the usleep() call (which is IMHO the part that would be considered "bad practice").

    Say you were waiting for data from a file or some other kind of stream that blocks. You could do this:

    while (($str = fgets($fp)) === FALSE) continue;
    // Handle the event here
    

    Really, PHP is the wrong language for doing stuff like this. But there are situations (I know because I have dealt with them myself) where PHP is the only option.

提交回复
热议问题