全局检查 PHP stdClass 中的有效属性?

发布于 2024-12-16 16:37:40 字数 144 浏览 3 评论 0原文

是否可以从 PHP stdClass 检查属性?我有一些模型正在作为 stdClass 生成。使用它们时,我想检查我调用的属性是否存在于某种核心类中。我注意到 __get 被 stdClass 忽略...

如何检查 stdClass 的属性是否存在于对象中?

Is it possible to check properties from a PHP stdClass? I have some models which are being generated as an stdClass. When using them I would like to check if the properties I'm calling exist in some kind of Core-class. I've noticed __get is ignored by the stdClass...

How can properties from a stdClass be checked if they exist in the object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

旧时光的容颜 2024-12-23 16:37:40

StdClass 对象仅包含属性,而不包含代码。所以你不能从它们“内部”编写任何代码。所以你需要解决这个“缺点”。根据生成这些类的内容,这可以通过“重载”数据(例如使用装饰器)来完成,从而提供您正在寻找的功能:

class MyClass
{
    private $subject;
    public function __construct(object $stdClass)
    {
        $this->subject = $stdClass;
    }
    public function __get($name)
    {
        $exists = isset($this->subject->$name);
        #...
    }
}

$myModel = new MyClass($model);

StdClass objects contain only porperties, not code. So you can't code anything from "within" them. So you need to work around this "shortcomming". Depending on what generates these classes this can be done by "overloading" the data (e.g. with a Decorator) providing the functionality you've looking for:

class MyClass
{
    private $subject;
    public function __construct(object $stdClass)
    {
        $this->subject = $stdClass;
    }
    public function __get($name)
    {
        $exists = isset($this->subject->$name);
        #...
    }
}

$myModel = new MyClass($model);
烟花肆意 2024-12-23 16:37:40

使用 get_object_vars() 迭代 stdClass 对象,然后使用 property_exists() 函数查看当前属性是否存在于父类中。

Use get_object_vars() to iterate through the stdClass object, then use the property_exists() function to see if the current property exists in the parent class.

獨角戲 2024-12-23 16:37:40

只需将其转换为数组

$x = (array) $myStdClassObject;

即可使用所有常见的数组函数

Just cast it to an array

$x = (array) $myStdClassObject;

Then you can use all the common array functions

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文