Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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.

Just cast it to an array

$x = (array) $myStdClassObject;

Then you can use all the common array functions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top