I want to create a daemon constructor in PHP.
class DAEMON {
var host;
var port;
function __construct($host, $port) {
$this -> host = $host;
$this -> port = $port;
}
function start() {
while (true) {
$this->loop();
}
}
function loop() {
}
}
In addition to passing the $host and $port parameters like
$server = new DAEMON("127.0.0.1", 9000);
$server -> start();
I want somehow to pass the loop() function as a 3rd parameter, so it overwrites the loop() function or inject code inside it.
I have tried
$server = new DAEMON("127.0.0.1", 9000, function() {
// function() can't take any parameters
// I cant use $server variable here
});
$server -> start();
and
$server = new DAEMON("127.0.0.1", 9000);
$server::loop = function() {
//not working, it's not javascript
};
$server->start();
Neither work. How can I do it? I have struggled many hours trying to find a solution..
You can call the
use
language construct to pass arguments to the anonymous functions. In your case, if you wanted to use the$server
variable, then you could do ..... but for this to work, your
DAEMON{}
class should have a third parameter in the constructor that acceptscallable
type..