Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global check for valid properties in a PHP stdClass?

Tags:

php

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?

like image 546
Ben Fransen Avatar asked Feb 22 '26 23:02

Ben Fransen


2 Answers

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);
like image 96
hakre Avatar answered Feb 25 '26 12:02

hakre


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!