php - PHP 如何从其他脚本访问 $Instance 变量?(棘轮)
问题描述
我有一个带有静态实例属性(Ratchet WebSocket 控制器)的 PHP 脚本,我想从另一个脚本访问该脚本的实例,我该怎么做?(以下代码生成该类的新 $Instance 而不是原来的)
(我想实现这一点,所以我可以从 WebSocket 控制器访问客户端列表)
(我正在关注本教程:http ://socketo.me/docs/hello-world )
索引.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();
?>
作曲家.json
{
"autoload": {
"psr-4": {
"MyApp\\": "src"
}
},
"require": {
"cboden/ratchet": "^0.4.3"
}
}
解决方案
推荐阅读
- javascript - 我可以使用 forEach 更改许多变量吗?
- python - Django期初余额计算
- javascript - 如何将 JSON 数据插入表单字段
- regex - 正则表达式 - 如何确保字符串末尾没有点?
- java - 如何在java中检查a html标签是否有结束标签?
- angular - Angular6(点击)在div的情况下不传递事件
- python - Python markdown 强制执行
- 无需前面的空行
- angular - x分钟后如何在没有用户交互的情况下刷新角度页面?
- airflow - 气流 apply_defaults 装饰器报告 参数是必需的
- wordpress - 使用 nginx 将搜索页面重定向到搜索结果页面