问题描述
我有一个带有静态实例属性的 PHP 脚本(一个 Ratchet WebSocket 控制器),我想从另一个脚本访问该脚本实例,我该怎么做? (以下代码生成该类的新 $Instance 而不是原来的)
(我想实现这一点,以便我可以从 WebSocket 控制器访问客户端列表)
(我正在学习本教程:http://socketo.me/docs/hello-world)
index.PHP
<!DOCTYPE html>
<html lang="en">
<head>
<Meta charset="UTF-8">
<Meta http-equiv="X-UA-Compatible" content="IE=edge">
<Meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>test</h1>
<?PHP
require dirname(__DIR__) . '/vendor/autoload.PHP';
require '/var/www/html/test/src/Chat.PHP';
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$obj = MyApp\Chat::getInstance();
var_dump($obj);
foreach ($obj->clients as $client) {
var_dump($client);
}
?>
</body>
</html>
/src/Chat.PHP
<?PHP
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
public static $instance = null;
public $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public static function getInstance()
{
if (self::$instance == null)
{
self::$instance = new Chat();
}
return self::$instance;
}
public function onopen(ConnectionInterface $conn) {
// Store the new connection to send messages to later
$this->clients->attach($conn);
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from,$msg) {
$numRecv = count($this->clients) - 1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n",$from->resourceId,$msg,$numRecv,$numRecv == 1 ? '' : 's');
foreach ($this->clients as $client) {
if ($from !== $client) {
// The sender is not the receiver,send to each client connected
$client->send($msg);
}
}
}
public function onClose(ConnectionInterface $conn) {
// The connection is closed,remove it,as we can no longer send it messages
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn,\Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
?>
/bin/chat-server.PHP
<?PHP
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\Chat;
require dirname(__DIR__) . '/vendor/autoload.PHP';
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),8080
);
$server->run();
?>
composer.json
{
"autoload": {
"psr-4": {
"MyApp\\": "src"
}
},"require": {
"cboden/ratchet": "^0.4.3"
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)