How to implement event driven code in PHP?

Is it possible to implement an event driven program in PHP?

Something like javascript.

As an example, try opening socket(open_socket) and running a few other command(do_something_else) instead of waiting for a response to the socket request. After receiving a success response, execute callback_execute .

 //-------------------------------------------------------------------- public function open_socket(){ $this->socketResource = fsockopen($this->nodeIp,$this->portNumber); } public function callback_execute(){ fputs($this->socketResource,$command); } public function do_something_else{ xxxxx } //-------------------------------------------------------------------- Non_blocking_function($obj->open_socket(),$obj->callback_execute()); $obj->do_something_else(); 
+4
source share
1 answer

In PHP, there is only one thread. Therefore, doing something useful while waiting for an event is not possible in PHP.

Some workarounds are available, but probably not very reliable - especially if you plan on writing portable code. I assume that workarounds are risky as the language does not have the concept of concurrency. Therefore, it is best to write multi-threaded code in another language (Java, Scala, ...) and use PHP only to display prepared results (if at all use PHP for such problems).

+3
source

Source: https://habr.com/ru/post/1391323/


All Articles