Ben
Ben

Reputation: 11208

Global check for valid properties in a 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?

Upvotes: 2

Views: 2313

Answers (3)

KingCrunch
KingCrunch

Reputation: 132011

Just cast it to an array

$x = (array) $myStdClassObject;

Then you can use all the common array functions

Upvotes: 0

hakre
hakre

Reputation: 198119

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

Upvotes: 6

user142162
user142162

Reputation:

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.

Upvotes: 5

Related Questions