简体   繁体   English

抛出异常后无法访问类的属性

[英]Unable to access property of a class after it throws exception

I have a PHP class which for this example I'm just calling MyClass . 我有一个PHP类,在此示例中,我只是调用MyClass If something goes wrong in this class, it throws an exception which I'm catching. 如果该类出现问题,它将引发我正在捕获的异常。 In this catch block, I need to access some public class properties of MyClass but for some reason they're all returning NULL . 在此catch块中,我需要访问MyClass一些公共类属性,但由于某些原因,它们都返回NULL Code below. 下面的代码。

try {
    $myClass= new \sys\global\MyClass($id);
} catch (Exception $e) {
    die(var_dump($myClass->reading));
}

The above is printing NULL to the page, even though reading is a public property of MyClass : 以上是打印NULL页面,即使reading是一个公共财产MyClass

namespace sys\global;

class MyClass {
    public $reading = 10;

    // ... other class code
}

I've even done die(var_dump($this->reading)) inside the class just before the exception is thrown and it has the value 10 . 我什die(var_dump($this->reading))在抛出异常之前就已经在类内完成了die(var_dump($this->reading)) ,它的值是10

Does throwing an exception in a class destroy it? 在类中抛出异常会破坏它吗?

If an exception is thrown inside the constructor, the object is not created. 如果在构造函数内引发异常,则不会创建该对象。 ie You can't access the attributes of an object that does not exist. 即,您无法访问不存在的对象的属性。

Depending on what the exception was, you may not be able to access the members. 根据异常的不同,您可能无法访问成员。 It would appear in this situation that your exception is caused in the constructor of $myClass , so I doubt your object is getting created properly, therefore meaning you can't access its properties. 在这种情况下,您的异常似乎是在$myClass的构造函数中引起的,因此我怀疑您的对象是否正确创建,因此意味着您无法访问其属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM