问题
This is a followup question to this question
If I declare this as a singleton class:
// Server.php
class Server {
private $stopper;
private static $instance;
public static getInstance() {
if(!isset(self::$Server))
self::$Server = new static();
return self::$Server;
}
public function setStopper() { $this->stopper = TRUE; }
public function startServer() {
$self = $this;
$consumer = new Consumer();
$consumer->onConsume(function($data) use($self, $consumer) {
// some processing
if($self->getStopper()) { // always false
$consumer->stop();
$self->stopServer();
}
});
$consumer->consume();
}
public function stopServer() { ... }
}
And used following script to start the server:
// start.php
$server = Server::getInstance();
$server->startServer();
And following script to set the stopper:
// stop.php
$server = Server::getInstance();
$server->setStopper();
It doesn't work: the stopper is still false (tried echo
ing)! Also I have tried using sessions instead.
// start.php
$server = new Server();
session_start();
$_SESSION['server'] = $server;
session_write_close();
$server->startServer();
// stop.php
session_start();
$server = $_SESSION['server'];
$server->setStopper(TRUE);
But running the stop.php throws following error: Undefined index: server
回答1:
Thanks @Maximus2012 and @Sammitch.
I got an idea from the following thread from Google groups
https://groups.google.com/d/msg/phirehose-users/dvCZ9EvCNA8/nOiv3m2ByAEJ
I used an external .txt
file to store a flag and set the stopper instead of all this fiasco ;)
Update
I found out why its not possible to work with singletons in this case. Every time php is invoked, a separate process (or thread, depending on the server) is created to handle that request i.e. separate process(or threads) for start.php
and stop.php
and they can't access same singleton due to "inter process privacy"!
But if I run start.php and stop.php as a single process it works, as expected!
来源:https://stackoverflow.com/questions/29374529/php-dynamically-update-singleton-class-value