无法通过异常对象访问类变量


Unable to access the class variable through the exception object

下面是异常对象的var_dump

object(Aws'S3'Exception'S3Exception)[98]
  private 'response' (Aws'Exception'AwsException) => 
    object(GuzzleHttp'Psr7'Response)[90]
      private 'reasonPhrase' => string 'Conflict' (length=8)
      private 'statusCode' => int 409
      private 'headers' => 
        array (size=6)
          'x-amz-request-id' => 
            array (size=1)
              ...
          'x-amz-id-2' => 
            array (size=1)
              ...
          'content-type' => 
            array (size=1)
              ...
          'transfer-encoding' => 
            array (size=1)
              ...
          'date' => 
            array (size=1)
              ...
          'server' => 
            array (size=1)
              ...
      private 'headerLines' => 
        array (size=6)
          'x-amz-request-id' => 
            array (size=1)
              ...
          'x-amz-id-2' => 
            array (size=1)
          ....
          ....

变量的类型是 object ,所以当我尝试访问response变量时:

catch(Exception $exc) {
        var_dump($exc);
        echo($exc->response); // Access response variable
}

我得到 :

 Undefined property: Aws'S3'Exception'S3Exception::$response

为什么我无法访问类变量?

不能直接访问private变量。但是,您可以在此处使用公共get方法。

$exc 是一个 Aws'S3'Exception'S3Exception 类对象,它是 Aws'Exception'AwsException 的子类。

通过您的代码:

catch(Exception $exc) {
    var_dump($exc);
    echo($exc->getResponse()); //Get the received HTTP response if any
}

更好的方法是:

catch (AwsException $e) {
    // This catches the more generic AwsException. You can grab information
    // from the exception using methods of the exception object.
    echo($exc->getResponse());
    echo($exc->getStatusCode());
}

参考文档