首页 > 解决方案 > PHP 将对象从页面传递到套接字

问题描述

我正在使用其功能性 MVC 模型将功能整合到现有平台中。事实是我正在聊天中工作,为此我使用PHP Sockets

我无法更改 MVC 结构中的任何内容,但我需要将socket.php两个对象放入我的文件中index.php

这些对象包含用户不应该看到的敏感信息。index.php位于root_folder/subfolder/index.phpsocket.php位于root_folder/another_subfolder/third_subfolder/socket.php

索引.php

<?php
...

$object1 = new Object1();
$object2 = new Object2();

套接字.php

<?php
...

class Socket extends MyOwnSocketClass{

    protected function onmessage($message){

        // I need these two objects here

    }

}

...

$socket = new Socket($host, $port);
try { $socket->run(); }
catch (Exception $e) { $socket->stdout($e->getMessage()); }

然后,从我php -q root_folder/another_subfolder/third_subfolder/socket.php用来启动套接字的终端,一切正常,客户端连接没有问题。但与此同时,我试图将这两个对象index.phpsocket.php...

套接字.php

require '../subfolf/index.php'; // Error failed open stream
require 'root_folder/subfolder/index.php'; // Undefined variable $object1
/*Using sessions*/ $_SESSION['object1']; // Undefined index object1
/*Using globals*/ $_GLOBALS['object1']; // Call to method in null

总之,我不能使用 require,我不能使用 $_SESSION,我不能使用 ../ 上传目录中的级别,如果我在 index.php 中插入套接字,则页面将无限加载。

标签: phpsocketsobjectwebsocket

解决方案


我将假设这index.php实际上是一个输出内容的页面。在这种情况下,当您使用require()它时,它会发送其输出,这就是它破坏您的流的原因。

如果你有某种共享对象/类,你应该把它放在它自己的文件中,你可以根据需要将它require()放在两个文件index.phpsocket.php。该文件不应该输出任何东西......它应该只包含您需要在两个上下文中包含的 PHP 代码。


推荐阅读