gpt4 book ai didi

php - __get 魔术方法 - 如何抛出和捕获属性重载的错误?

转载 作者:行者123 更新时间:2023-12-02 00:15:33 31 4
gpt4 key购买 nike

我通过利用 __get 来定义当访问不存在的属性时会发生什么神奇的方法。

所以如果 $property->bla不存在我会得到null .

return (isset($this->$name)) ? $this->$name : null;

但我想抛出并捕获 $property->bla->bla 的错误当我知道 $property->bla不存在。

return (isset($this->$name)) ? $this->$name : null;我将在下面收到此错误,
<b>Notice</b>:  Trying to get property of non-object in...

所以我使用 throw and catch我类的错误,

类属性
{
public function __get($name)
{
//return (isset($this->$name)) ? $this->$name : null;

try {
if (!isset($this->$name)) {
throw new Exception("Property $name is not defined");
}
return $this->$name;
}
catch (Exception $e) {

return $e->getMessage();
}
}

}

但结果不是我想要的,因为它 throw错误信息 ("Property $name is not defined")而不是 null$property->bla .

我怎样才能让它抛出错误消息 只有$property->bla->bla , $property->bla->bla->bla , 等等?

最佳答案

你不能。

__get()范围内功能,你只知道$property->blah .你不知道它后面是什么,因为那是语言的功能。

请注意 $foo = $property->blah->blah2->blah3 上的评估顺序:

  • $temp1 = $property->blah;
  • $temp1 = $temp1->blah2;
  • $foo = $temp1->blah3;

  • 当然, $temp1是虚构的,但这实质上是执行该语句时发生的情况。您的 __get() call 只知道该列表中的第一个调用,仅此而已。您可以做的是处理调用方的错误,使用 property_exists() 或查看 null :
    $temp = $property->blah;
    if( $temp === null || !property_exists( $temp, 'blah2')) {
    throw new Exception("Bad things!");
    }

    请注意 property_exists()如果在 $temp 中返回的对象将失败还靠 __get() ,但这在 OP 中并不清楚。

    关于php - __get 魔术方法 - 如何抛出和捕获属性重载的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13383281/

    31 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com