php类的多功能吸气剂

我写了某种安全的类,可以接收stdClass类型的内容:

class SafeContent extends stdClass {
​
    /** @var stdClass $content */
    protected $content;
​
    public function __construct(stdClass $content) {
        $this->content = $content;
    }
​
    public function __get($name) {
        if ($this->content->name == null) {
             // do something
        }
    }
​
}

,并且我希望SafeContent的getter可以捕获类似$safeContent->someField->anotherField->lastField的获取操作,因此name中的__get参数将是someField->anotherField->lastField或类似的东西。有办法解决这个问题吗?

cobol_12121 回答:php类的多功能吸气剂

无法使用一个参数在一个__get中获得所有字段,但是您可以将每个对象强制转换为SafeContent类,因此每个顺序调用都将输入您的类的getter:

// inside __get function
if (!isset($this->content->$name) || $this->content->$name == null) {
    // do something,probably throw an exception
}

if ($this->content->$name instanceof stdClass) {
    // return the instance of your class with appropriate content
    $component = new self($this->content->$name);
    return $component;
}

return $this->content->$name;
本文链接:https://www.f2er.com/2987811.html

大家都在问