无法访问对象 PHP 的私有 属性

Cannot access private property of an object PHP

我目前正在使用 Ratchet websocket,当我尝试打印连接时,我得到了这个对象,我想得到 uri->query 字段,但是当我尝试这样做时,它给了我一个错误,我无法访问私人 属性.

我的代码:

GuzzleHttp\Psr7\Request {#772
  -method: "GET"
  -requestTarget: null
  -uri: GuzzleHttp\Psr7\Uri {#773
    -scheme: "http"
    -userInfo: ""
    -host: "localhost"
    -port: 8090
    -path: "/"
    -query: "id=3"
    -fragment: ""
  }
    "Pragma" => array:1 [
      0 => "no-cache"
    ]
    "Cache-Control" => array:1 [
      0 => "no-cache"
    ]
    "Upgrade" => array:1 [
      0 => "websocket"
    ]
    "Origin" => array:1 [
      0 => "http://127.0.0.1:8000"
    ]
    "Sec-WebSocket-Version" => array:1 [
      0 => "13"
    ]
    "User-Agent" => array:1 [
      0 => "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36"
    ]
    "Accept-Encoding" => array:1 [
      0 => "gzip, deflate, br"
    ]
    "Accept-Language" => array:1 [
      0 => "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7,hy;q=0.6"
    ]
    "Sec-WebSocket-Key" => array:1 [
      0 => "apMgrSRt1GBHX5Nhj19gHQ=="
    ]
    "Sec-WebSocket-Extensions" => array:1 [
      0 => "permessage-deflate; client_max_window_bits"
    ]
  ]
  -protocol: "1.1"
  -stream: null
}

这是我得到的错误:

Symfony\Component\Debug\Exception\FatalThrowableError  : Cannot access private property GuzzleHttp\Psr7\Request::$uri

  at C:\xampp\htdocs\laravel_\my_project\app\Http\Controllers\WebSocketController.php:34
    30|
    31|     public function onOpen(ConnectionInterface $conn)
    32|     {
    33|
  > 34|         dd($conn->httpRequest->uri);
    35|
    36|         $this->clients->attach($conn);
    37|         $this->users[$conn->resourceId] = $conn;
    38|     }

  Exception trace:

  1   App\Http\Controllers\WebSocketController::onOpen(Object(Ratchet\WebSocket\WsConnection))
      C:\xampp\htdocs\laravel_\my_project\vendor\cboden\ratchet\src\Ratchet\WebSocket\WsServer.php:142

  2   Ratchet\WebSocket\WsServer::onOpen(Object(Ratchet\Server\IoConnection), Object(GuzzleHttp\Psr7\Request))
      C:\xampp\htdocs\laravel_\my_project\vendor\cboden\ratchet\src\Ratchet\Http\HttpServer.php:51

如何获取 query 字段的值?

该变量是私有的,因此您无法从 class 外部访问它。 (了解 variable scope

但在您的情况下,您使用的是 Guzzle HTTP 请求对象,因此 doc 表示:

public getQuery ( mixed $asString = false )

Get the collection of key value pairs that will be used as the query string in the request

因此您可以只使用 getQuery 从对象中获取查询。

您可以通过以下方式访问:

$conn->httpRequest->getUri()->getQuery();

Read more here..