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

时间:2019-07-11 09:28:09

标签: php oop private

我当前正在使用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字段的值?

1 个答案:

答案 0 :(得分:1)

该变量是私有变量,因此您不能从类外部访问它。 (了解有关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从对象获取查询。