2

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?

3
  • 1
    Maybe I don't understand what you mean with "_get is ignored by the stdClass", but __get() is _not implemented in stdClass. Commented Nov 17, 2011 at 14:58
  • I did'nt knew that. Thanks for clearing that up :) Commented Nov 17, 2011 at 15:01
  • If I understand your comments below right: You can also implement __isset() Commented Nov 17, 2011 at 15:21

3 Answers 3

6

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Yes it's a pattern. If you describe more in your class where and how those stdClass objects are created this can be even simplified under certain circumstances.
This seems like a solution. Thanks! Accepted + 1:)
5

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.

4 Comments

But where to store it globally? Because __get() is ignored..?
@BenFransen: Can you post a dump of an instance of stdClass, as well as the Core-class you're referring to.
the stdClass is generated by mysql_fetch_object(). In a class called System_Core (from which every class extends) there are the magic functions __get() and __set().
The Decorator pattern is what I'm looking for. Thanks for your help, +1 :)
0

Just cast it to an array

$x = (array) $myStdClassObject;

Then you can use all the common array functions

1 Comment

The goal was actually to have arrays as an object ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.