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

时间:2016-03-15 06:47:16

标签: php class object exception amazon-web-services

以下是异常对象的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

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

1 个答案:

答案 0 :(得分:0)

您无法直接访问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());
}

Reference Doc